C Programming

PASSING ARRAYS TO FUNCTIONS
The following program demonstrates how to pass an array to a function.


	/* example program to demonstrate the passing of an array */
	#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 );
	}


	Sample Program Output
	Enter 5 numbers
	7 23 45 9 121
	Maximum value is 121

Note: The program defines an array of five elements (values) and initializes each element to the users inputted values. The array values is then passed to the function. The declaration


	int  maximum( int values[5] )

defines the function name as maximum, and declares that an integer is passed back as the result, and that it accepts a data type called values, which is declared as an array of five integers. The values array in the main body is now known as the array values inside function maximum. IT IS NOT A COPY, BUT THE ORIGINAL.

This means any changes will update the original array.

A local variable max_value is set to the first element of values, and a for loop is executed which cycles through each element in values and assigns the lowest item to max_value. This number is then passed back by the return statement, and assigned to max in the main section.


©Copyright B Brown. 1984-1999. All rights reserved.