Passing Array to a Function in Different ways

ad+1


There are three ways to pass an array to a function. Each way and its program examples are give below:

Here i am sharing a simple program that will initialize and array and then will send that array to a function which will make square of elements of that array.

These three method include passing array to function using pointers. Passing array to function simply with name, And passing array to function with size.

 

 Method 1:

#include <iostream>
using namespace std;

void function(int arr[]);


int main()
{
  int arr[10];

  for(int i=0; i<10; i++)
   arr[i]=i+1;

  function(arr);
 
  // New Values of Array
  for(int i=0; i<10; i++)
   cout<<arr[i]<<endl;
    return 0;
}

void function(int arr[])
{
      for(int i=0; i<10; i++)
       arr[i]= arr[i] * arr[i];
}



Method 2:

#include <iostream>
using namespace std;

void function(int *arr);


int main()
{
  int arr[10];

  for(int i=0; i<10; i++)
   arr[i]=i+1;

  function(arr);
 
  // New Values of Array
  for(int i=0; i<10; i++)
   cout<<arr[i]<<endl;
    return 0;
}

void function(int *arr)
{
      for(int i=0; i<10; i++)
       arr[i]= arr[i] * arr[i];
}


 

Method 3:

#include <iostream>
using namespace std;

void function(int *arr, int size);

int main()
{
  int arr[10];

  for(int i=0; i<10; i++)
   arr[i]=i+1;

  function(arr, 10);
 
  // New Values of Array
  for(int i=0; i<=9;i++)
   cout<<arr[i]<<endl;
    return 0;
}

void function(int *arr, int size)
{
      for(int i=0; i<size; i++)
       arr[i]= arr[i] * arr[i];
}






 

Output:

 


8 comments: Leave Your Comments