Array and Function in C ?


There are multiple ways to pass one-dimensional arrays as arguments in C. We need to pass the array to a function to make it accessible within the function. If we pass an entire array to a function, all the elements of the array can be accessed within the function. Single array elements can also be passed as arguments. This can be done in exactly the same way as we pass variables to a function. There are two way to pass array to function
Passing individual Elements of the array.
Passing the whole array.


Passing individual Elements of the 1D array to function

All array elements can be passed as individual elements to the function like any other variable.
Q.) W.A.P for passing individual elements of the 1D array to function
 #include<stdio.h>
 #include<conio.h>
 void display(int,int);
 void main()
 {
 int arr[]={4, 5, 6, 3, 2};
 // passing second and third elements to the function 
 display(arr[1], arr[2]); 
 }
 void display(int x, int y)
 {
 printf(“%d%d”,x,y);
 }   
 int sum(int arr[]);
 void main()
 {
 int r, arr[]={4, 5, 6, 3, 2};
 // passing array to  the function 
 r=sum(arr); 
 printf(“%d”,r);
 }
 int sum(int array[])
 {
 for(i=0;i<=4;i++)
 {
 s=s+array[i];
 }
 return s;
 }
Output


Passing 2D array to function


Q.) W.A.P for passing 2D array to function.
 int display(int arr[][]);
 void main()
 {
 int  arr[2][2];
 for(i=0;i<=1;i++)
 {
 for(j=0;j<=1;j++)
 {
 scanf(“%d”,&arr[i][j]);
 }
 }
 display(arr);
 }
 void display(int arr[2][2])
 {
 for(i=0;i<=1;i++)
 {
 for(j=0;j<=1;j++)
 {
 printf(“%d”,arr[i][j]);
 }
 printf(“\n”);
 }
 }
Output