Array and Functions

0 kayleighchristi November 25, 2020

As we know, the function accepts arguments. We are familiar with the variable arguments but here, We will learn how we can pass an array as arguments in the function.

In order to pass an array as an argument in the function, You have to mention the array name during the function call as mentioned below.

function_name(array_name);

Now we look at an example to make clear concepts on these topics. Here, We are passing two arrays a and b to the function sum().  This function will add the corresponding value of each array and print the output.

#include <stdio.h>
/* This function adds the corresponding
* elements of both the arrays and
* print te output on screen.
*/
void sum(int arr1[], int arr2[]){
int temp;
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];      printf("%d\n", temp[i]);
}
}

int main(){
int a = {5, 10, 15, 20 ,25};
int b = {1, 2, 3, 4, 5};
//Passing two arrays to the function
sum(a, b);
return 0;
}

The output of the above program is:

6
12
18
24
30

Passing two-dimensional array to the function

Now, we will learn how to pass two-dimensional arrays to the function. Here, We are passing a multidimensional array to the function square() that prints the square of each element of a two-dimensional array.

#include <stdio.h>
#include <math.h>

/* This function prints the square of each
* of the elements of the two-multidimensional array
*/
void square(int arr){
int temp;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
temp = arr[i][j];
printf("%d\n", pow(temp, 2));
}
}
}
int main(){
int arr = {
{1, 2, 3},
{4, 5, 6}
};
square(arr);
return 0;
}

The output of the above program is:

1
4
9
16
25
36