- Write a C program to find maximum and minimum element of an array.
- How to find max and min element of an array using for loop.
Required Knowledge
- C printf and scanf functions
- For loop in C
- Relational Operators in C
Algorithm to find maximum and minimum elements of an array
Let inputArray is an integer array having N elements.
- Declare two integer variable ‘max’ and ‘min’. Initialize ‘max’ and ‘min’ with first element of input array(inputArray[0]).
- Using for loop, we will traverse inputArray from array from index 0 to N-1.
- If current element is more than max, then update max
if(inputArray[i] > max) max = inputArray[]; - Else If, current element is less than min, then update min
if(inputArray[i] < min) min = inputArray[i];
C program to find maximum and minimum element of an array
/* * C Program to find maximum array elements */ #include <stdio.h> #include <conio.h> int main(){ int inputArray[500], elementCount, counter, max, min; printf("Enter Number of Elements in Array\n"); scanf("%d", &elementCount); printf("Enter %d numbers \n", elementCount); /* Read array elements */ for(counter = 0; counter < elementCount; counter++){ scanf("%d", &inputArray[counter]); } max = min = inputArray[0]; for(counter = 1; counter < elementCount; counter++){ if(inputArray[counter] > max) max = inputArray[counter]; else if(inputArray[counter] < min) min = inputArray[counter]; } printf("Maximum Element : %d\n", max); printf("Minimum Element : %d", min); getch(); return 0; }
Output
Enter Number of Elements in Array 8 Enter 8 numbers 2 4 -1 -6 9 12 0 7 Maximum Element : 12 Minimum Element : -6