C program to find maximum value in an array

      Before learning how to find maximum value in an array, let us brush up what an array is. Array is a collection of data of similar type. Similar type refers to the same datatype i.e. if you gonna create an array of type int, only the int values can me accommodated into it. The size of array is fixed. You can specify the length of an array during its creation.

The maximum value in an array is found by the below logic which is better to understand when compared to other logical approach. Initially, the first number of an array is assumed to be the maximum value and then this value is checked against all the numbers of an array. If any number is greater than the assumed maximum value then that number will be the maximum value. Using this logic maximum value in an array is found.

C program to find maximum value in an array



Source Code :

#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] );       //Step 1
	max = maximum( values,5 ); //Step 2
	printf("\nMaximum value is %d\n", max ); // Step 5
	return 0;
}	
/**** function definition ****/
int maximum(int values[], int n)
{
	int max_value, i;
	max_value = values[0];   //Step 3
	for( i = 1; i < n; ++i ) //Step 4
		if( values[i] > max_value ) //Step 4(i)
			max_value = values[i];
	return max_value;
}


edit-code-image

Sample Test cases :

1.  Enter 5 numbers
    3 
    5
    78
    23
    1
   Maximum value is 78

2. Enter 5 numbers
    3
    2
    6
    8
    8
  Maximum value is 8

Explanation:

Step 1 : The array is read from the user using scanf() function.

Step 2 : The function is called from the main program with array and no_of_elements of an array as arguments.

Step 3 : Initially the first value of an array is assumed to be the maximum value.

Step 4 : This loop helps in checking all the number of an array against assumed maximum value.

Step 4(i): If any value is greater than assumed maximum value then that number will be the maximum value.

Step 5 : Finally the maximum value of an array is printed on the output screen using printf() function.

More Content:Arrays
Explore C Programs:C Programs