C program to find maximum and minimum element in an array


 /*
Alamgir Hossain
Lecturer, Dept. of CSE, Prime University.

C program to find maximum and minimum element in array.
        Example: 20, 17, 10, 5, 50
        Max: 50
        Min: 5


Logic:
        1. Input size and element in array, store it in some variable say size and arr.
        2. Declare max and min to store maximum and minimum element.
        Assume first array element as maximum and minimum both,
        so, max = arr[0] and min = arr[0].
        3. Run loop from first to last array element i.e. 0 to size - 1
        4. Inside loop check each array elements,
        if (arr[i] > max), then update max = arr[i];
        if (arr[i] < min), then update min = arr[i];
*/
#include<stdio.h>
int main()
{
        int size, arr[100], max, min, i;
        printf("Enter the size of the array: ");
        scanf("%d", &size);
        printf("Enter the elements of the array: ");
        for(i = 0; i < size; i++){
                scanf("%d", &arr[i]);
        }
        max = min = arr[0];
        for(i = 0; i < size; i++){
                if(max < arr[i]){
                        max = arr[i];
                }
                if(min > arr[i]){
                        min = arr[i];
                }
        }
        printf("Maximum is : %d\n", max);
        printf("Minimum is: %d\n", min);
        return 0;
}



1 comment: