Arrays and functions

In C programming, an array can be passed as an argument to a function.  We can pass a single array element of one dimensional or multi-dimensional array, or we can pass entire array to a function.

In this chapter we will learn how to pass an array as an argument to a function.

 

Passing a single array element of one dimensional array to a function. As we have read in function. There are two method to pass an argument to a function

Method 1: Pass by value

#include<stdio.h>void print_array_element(int array_element){

printf(“%d\n”, array_element);

}

int main()

{

int num[5] = {10, 20, 30, 40, 50};

/* Passing a single array element at index 1 */

print_array_element(num[1]);

return 0;

}

Output : 20

 

Method 1: Pass by reference

#include<stdio.h>void print_array_element(int *array_element){

printf(“%d\n”, *array_element);

}

int main()

{

int num[5] = {10, 20, 30, 40, 50};

/* Passing a single array element at index 1, using call by reference  */

print_array_element(&num[1]);

return 0;

}

 

Output : 20

 

Also we can pass entire array to a function as an argument. While passing an entire array to a function, the name of the array is passed as an argument means starting address of array.

Example program of passing an entire array of one dimensional array to a function.

Write a program to find sum of the numbers of an array.#include<stdio.h>int sum_array_element(int array_elements[]){

int i,sum = 0;

for(i=0; i<=4; i++)

sum = sum + array_elements[i];

return sum;

}

int main()

{

int sum;

int num[5] = {10, 20, 30, 40, 50};

/* Passing an entire array, only name of array is passed */

sum = sum_array_element(num);

printf(“Sum = %d\n”,sum);

return 0;

}

 

Output : Sum = 150

 

Passing a multi-dimensional array to a function as an argument.

Similarly as one dimensional array, we can pass an single element of multi-dimensional array.#include<stdio.h>void print_array_element(int array_element){

printf(“%d\n”, array_element);

}

int main()

{

int num[4][3] = {1,2,3,4,5,6,7,8,9,10,11,12};

/* Passing a single array element at index [2][1] i.e 8 */

print_array_element(num[2][1]);

return 0;

}

Output : 8

 

Passing an entire two dimensional array to a function as an argument

#include<stdio.h>int sum_array_element(int array_elements[][]){

int i,j,sum = 0;

for(i=0; i<4; i++)

    for(j=0; j<3; j++)

        sum = sum + array_elements[i][j];

return sum;

}

int main()

{

int sum;

int num[4][3] = {1,2,3,4,5,6,7,8,9,10,11,12};

/* Passing an entire array, only name of array is passed */

sum = sum_array_element(num);

printf(“Sum = %d\n”,sum);

return 0;

}

Output : Sum = 78

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.