C passing array element to function

Passing array element by element to function :

  1. Individual element is passed to function using Pass By Value parameter passing scheme
  2. Original Array elements remains same as Actual Element is never Passed to Function. thus function body cannot modify Original Value.
  3. Suppose we have declared an array ‘arr[5]’ then its individual elements are arr[0],arr[1]…arr[4]. Thus we need 5 function calls to pass complete array to a function.

Tabular Explanation :

Consider following array

int arr[5] = {11,22,33,44,55};
IterationElement Passed to FunctionValue of Element
1arr[0]11
2arr[1]22
3arr[2]33
4arr[3]44
5arr[4]55

C Program to Pass Array to Function Element by Element :

#include< stdio.h>
#include< conio.h>
//---------------------------------
void fun(int num)
{
printf("\nElement : %d",num);
}
//--------------------------------
void main()
{
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
 scanf("%d",&arr[i]);

printf("\nPassing array element by element.....");

for(i=0;i< 5;i++)
   fun(arr[i]);

getch();
}

Output :

Enter the array elements : 1 2 3 4 5
Passing array element by element.....
Element : 1
Element : 2
Element : 3
Element : 4
Element : 5

Disadvantage of this Scheme :

  1. This type of scheme in which we are calling the function again and again but with different array element is too much time consuming. In this scheme we need to call function by pushing the current status into the system stack.
  2. It is better to pass complete array to the function so that we can save some system time required for pushing and popping.
We can also pass the address of the individual array element to function so that function can modify the original copy of the parameter directly. [See : Parameter Passing – Pass by Address]

Live Example 2 : Passing 1-D Array Element by Element to function

#include<stdio.h>

void show(int b[3]);

void main()
{
int arr[3] = {1,2,3};
int i;
for(i=0;i<3;i++)
  show(arr[i]);
}

void show(int x)
{
printf("%d ",x);
}