How to send individual elements as an argument in C language?

CServer Side ProgrammingProgramming

The array is a group of related items that is stored with a common name.

Declaring array

The syntax used for declaring an array is as follows −

datatype array_name [size];

Initialization

An array can be initialized in two ways, which are as follows −

  • Compile time initialization
  • Runtime initialization

An array can also be initialized at the time of declaration as follows −

int a[5] = {100,200,300,400,500};

Function

A function is a self-contained block that carries out a specific well-defined task. The two ways of passing the arrays as arguments to functions are as follows −

  • Sending an entire array as argument to function.
  • Sending the individual elements as an argument to function.

Now, let us understand how to send the individual elements as an argument to function.

Sending individual elements as argument to function.

  • 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

Refer the program given below −

 Live Demo

#include<stdio.h>
main ( ){
   void display (int, int);
   int a[5], i;
   printf ("enter 5 elements");
   for (i=0; i<5; i++)
      scanf("%d", &a[i]);
      display (a [0], a[4]); //Sending individual array element using array name
   }
   void display (int a, int b){ //receiving individual array element
      printf ("first element = %d",a);
      printf ("last element = %d",b);
}

Output

When the above program is compiled together and executed, it produces the following result −

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

Example 2

Refer the program given below −

 Live Demo

#include<stdio.h>
main ( ){
   void display (int,int,int);
   int a[6], i;
   printf ("enter 5 elements");
   for (i=0; i<6; i++)
      scanf("%d", &a[i]);
   display (a[0],a[2],a[5]); // Sending individual array element using array name
}
void display (int a, int b,int c){//receiving individual array element
   printf ("first element = %d\n",a);
   printf ("middle element = %d\n",b);
   printf("last element = %d",c);
}

Output

When the above program is compiled together and executed, it produces the following result −

enter 5 elements
10
20
30
40
50
60
first element = 10
middle element = 30
last element = 60
raja
Published on 11-Mar-2021 12:31:39
Advertisements