C Program to print maximum and minimum element in array

Category: C Program

C Program to print maximum and minimum element in an array

C Program to find maximum and minimum elements in an array

#include <stdio.h>

void main()
{
    int arr[50], n, i, min, max;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter array elements-\n");
    for(i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    // asumming elements at arr[0] are the maximum and minimum numbers
    min = arr[0];
    max = arr[0];

    for (i = 1; i < n; i++)
    {
        // checking for minimum number
        if (arr[i] < min)
            min = arr[i];

        // checking for maximum number
        if (arr[i] > max)
            max = arr[i];
    }

    printf("\nMinimum number in the array is: %d\n", min);
    printf("Maximum number in the array is: %d", max);
}

Output

Enter number of elements: 5
Enter array elements-
2
3
1
4
5
Minimum number in the array is: 1
Maximum number in the array is: 5

Recommended Posts