How to send an entire array as an argument in C language?


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

Declaring array

The syntax 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 an argument to function.

  • Sending the individual elements as argument to function.

Now, let us understand how to send an entire array as an argument to function in C language.

Sending an entire array as argument to function

  • To send an entire array as argument, try to send the array name in the function call.

  • To receive an entire array, an array must be declared in the function header.

Example 1

Refer an example given below −

#include<stdio.h>
main ( ){
   void display (int a[5]);
   int a[5], i;
   clrscr( );
   printf ("enter 5 elements");
   for (i=0; i<5; i++)
      scanf("%d", &a[i]);
   display (a); // Sending entire array ‘a’ using array name
   getch( );
}
void display (int a[5]) {//receiving entire array
   int i;
   printf ("elements of the array are");
   for (i=0; i<5; i++)
      printf("%d ", a[i]);
}

Output

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

Enter 5 elements
10 20 30 40 50
Elements of the array are
10 20 30 40 50

Example 2

Following is the C program to print the elements in a reverse order from the array −

#include<stdio.h>
void main(){
   //Declaring the array - run time//
   int array[5],i;
   void rev(int array[5]);
   //Reading elements into the array//
   printf("Enter elements into the array: 
");    //For loop//    for(i=0;i<5;i++){       //Reading User I/p//       printf("array[%d] :",i);       scanf("%d",&array[i]);    }    //Displaying reverse order of elements in the array//    printf("The elements from the array displayed in the reverse order are :
");    rev(array); // Sending entire array ‘a’ using array name    getch(); } void rev(int array[5]){ //receiving entire array    int i;    for(i=4;i>=0;i--){       //Displaying O/p//       printf("array[%d] :",i);       printf("%d
",array[i]);    } }

Output

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

Enter elements into the array:
array[0] :23
array[1] :34
array[2] :12
array[3] :56
array[4] :12
The elements from the array displayed in the reverse order are:
array[4] :12
array[3] :56
array[2] :12
array[1] :34
array[0] :23

Updated on: 17-Mar-2021

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements