C Arrays & Function

In this tutorial, you will learn to pass arrays in C functions.  Through this tutorial, you will have knowledge about passing both two dimensional and one-dimensional arrays in functions. At the time, when we need to pass a list of elements as an argument to any function in C language, we will have to implement arrays. Now you will see how we can pass an array as an argument to a function.

If you have to pass a single dimensional array as an argument in a function, you will have to declare the formal parameter in one of the following three methods. Each of these declaration methods will produce the same results because each tells the compiler that an integer pointer is going to be received. similarly, we can also pass the multi-dimensional arrays as the formal parameters.

Method-1: Formal parameter as a single array element

Now let’s see an example where we will need to pass only one of the array element. Here, we will have to declare and define an array of integers in our main() function and pass one of the array element to a function. And our function will hence print the value of the element.

The above program will display the output as below:
Output:

5 is the roll passed through the function.

Method: 2 Formal parameters as an entire array element

In order to understand how we can pass an entire array of elements, let’s see the following example. In the program below, we will pass an entire element in the array through the name of the array. Our function will hence calculate the average of the elements in the array and print them. Which means we will only send in the name of the array as an argument. The name of the element is the address of the starting element of the array or we can also say the address of the element.

The above program will display the output as below:

Output:

Average marks of the students are = 89.000000

Method: 3 Formal parameters as a multidimensional array element

Now let’s consider a function which will take in the multidimensional array as an arguement. This program will ask the user to input the elements of the array in the main program. The elements of the array are hence passed as a whole to the function and the function will display those elements in the matrix form.

The above program will display its output as below:

Output:

Please enter 4 numbers for the array:

1

2

3

4

The complete array with elements entered in the main function is:

1                  2

3                  4

 

 

SHARE C Arrays & Function

You may also like...

Leave a Reply

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

Share