1-d arrays using functions
Passing individual array elements to a function
We can pass individual array elements as arguments to a function like other simple variables.
Example: #include <stdio.h> void check(int); void main() { int a[10],i; clrscr(); printf(“\n enter the array elements:”); for(i=0;i<10;i++) { scanf(“%d”,&a[i]); check(a[i]); } void check(int num) { if(num%2==0) printf(“%d is even\n”,num); else printf(“%d is odd\n”,num); } Output: enter the array elements: 1 2 3 4 5 6 7 8 9 10 1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even
Example: C program to pass a single element of an array to function #include <stdio.h> void display(int a) { printf("%d",a); } int main() { int c[]={2,3,4}; display(c[2]); //Passing array element c[2] only. return 0; } Output 2 3 4
Passing whole 1-D array to a function
We can pass whole array as an actual argument to a function the corresponding formal arguments should be declared as an array variable of the same type.
Example: #include <stdio.h> main() { int i, a[6]={1,2,3,4,5,6}; func(a); printf(“contents of array:”); for(i=0;i<6;i++) printf(“%d”,a[i]); printf(”\n”); } func(int val[]) { int sum=0,i; for(i=0;i<6;i++) { val[i]=val[i]*val[i]; sum+=val[i]; } printf(“the sum of squares:%d”, sum); } Output contents of array: 1 2 3 4 5 6 the sum of squares: 91