Programming Example
Write a program that uses a function to find the maximum value in an array.
Write a program that uses a function to find the maximum value in an array.
#include<stdio.h>
int maximum( int [],int ); /* function prototype */
int main(void)
{
int values[5], i, max;
printf("Enter 5 numbers\n");
for( i = 0; i < 5; ++i )
scanf("%d", &values[i] );
max = maximum( values,5 ); /* function call */
printf("\nMaximum value is %d\n", max );
return 0;
}
/**** function definition ****/
int maximum(int values[], int n)
{
int max_value, i;
max_value = values[0];
for( i = 1; i < n; ++i )
if( values[i] > max_value )
max_value = values[i];
return max_value;
}
Enter 5 numbers
5
6
4
2
3
Maximum value is 6
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.