How to pass individual elements in an array as argument to function in C language?

CServer Side ProgrammingProgramming

If individual elements are to be passed as arguments, then array elements along with their subscripts must be given in function call.

To receive the elements, simple variables are used in function definition.

Example 1

#include<stdio.h>
main (){
   void display (int, int);
   int a[5], i;
   clrscr();
   printf (“enter 5 elements”);
   for (i=0; i<5; i++)
      scanf("%d", &a[i]);
   display (a [0], a[4]); //calling function with individual arguments
   getch( );
}
void display (int a, int b){ //called function with individual arguments
   print f ("first element = %d",a);
   printf ("last element = %d",b);
}

Output

Enter 5 elements
   10    20    30    40    50
First element = 10
Last element = 50

Example 2

Consider another example for passing individual elements as argument to a function.

#include<stdio.h>
main (){
   void arguments(int,int);
   int a[10], i;
   printf ("enter 6 elements:\n");
   for (i=0; i<6; i++)
      scanf("%d", &a[i]);
   arguments(a[0],a[5]); //calling function with individual arguments
   getch( );
}
void arguments(int a, int b){ //called function with individual arguments
   printf ("first element = %d\n",a);
   printf ("last element = %d\n",b);
}

Output

enter 6 elements:
1
2
3
4
5
6
first element = 1
last element = 6
raja
Published on 08-Mar-2021 13:21:34
Advertisements