Site icon i2tutorials

Passing Arrays to Functions

Passing Arrays to Functions

 

Passing an entire array to function:

 

 

In C programming, a single array element or an entire array are often passed to a function. This can be done for both a one-dimensional array or a multi-dimensional array.

 

Example Program:

 

C program to pass a single element of an array to function.

 

#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main()
{
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]); /*Passing array element ageArray[2] only */
return 0;
}

 

Output:

 

 

Passing an entire one-dimensional array to a function:

 

While passing arrays as arguments to the function, only the name of the array is passed (starting address of the memory area is passed as an argument).

 

Example Program:

 

C program to pass an array containing the age of the person to a function.This function should find the average age and display the average age within the main function.

 

#include <stdio.h>
float average(float age[]);
int main()
{
float avg, age[] = { 20.5, 30, 45.6, 6, 40.5, 20 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return 0;
}float average(float age[])
{
int i;
float avg, sum = 0.0;
for (i = 0; i< 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}

 

Output:

 

 

Example Program:

 

Find out the max number using a 1D array to function.

 

#include <stdio.h>
int maximum( int [] ); /* ANSI function prototype */
int maximum( int values[5] )
{
int max_value, i;
max_value = values[0];
for(i = 0; i< 5; ++i )
if( values[i] >max_value )
max_value = values[i];
return max_value;
}
main()
{
int values[5], i, max;
printf("Enter 5 numbers\n");
for(i = 0; i< 5; ++i )
scanf("%d", &values[i] );
max = maximum( values );
printf("\nMaximum value is %d\n", max );
}

 

Output:

 

 

Exit mobile version