Passing array element by element to function :
- Parameter Passing Scheme : Pass by Value
- Individual element is passed to function.
- Suppose arr[5] is name of array then pass arr[0],arr[1] elements
- Original Array elements remains same .
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 :
- 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.
- 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]