Loading....
Coupon Accepted Successfully!

 

Passing Array Elements To A Function

We can pass elements to a function by using call-by-value or call-by-reference methods. In the call-by-value method, elements (values) of an array are passed to the function; whereas in the call-by-reference method, addresses of elements are passed to the function.

The following program demonstrates the call-by-value method:
 

12.7 Program to pass elements of an array to a function by using call by value.

#include<iostream.h>

#include<conio.h>

void display(int);

void main()

{

int num[5]={1,2,3,4,5},i;

clrscr();

cout<<“\nElements in the reverse order are as follows:”;

for(i=4;i>=0;i--)

{

display(num[i]);

}

}
void display(int x)
{
cout<<“ ”<<x;
}

OUTPUT
Elements in the reverse order are as follows: 5 4 3 2 1

Explanation: 
In the above program, individual elements of array num[5] are passed to the function display(int), and the same are displayed in the called function.
 
The following program demonstrates the call-by-reference method:
 

12.8 Program to pass elements of an array to a function by using call by reference.

#include<iostream.h>

#include<conio.h>

void display(int *);

void main()

{

int num[5]={1,12,3,4,5},i;

clrscr();

cout<<“\nElements of the array are as follows:”;

for(i=0;i<5;i++)

{

display(&num[i]);

}

}

void display(int *x)

{

cout<<“ ”<<*x;

}

OUTPUT
Elements of the array are as follows: 1 2 3 4 5

Explanation:
 In the above program, addresses of individual array elements are passed to the function display(int *). The x contains the address of an array element, and âx is the value stored at that address.





Test Your Skills Now!
Take a Quiz now
Reviewer Name