C program to find maximum and minimum element in array

Write a C program to input elements in an array from user, find maximum and minimum element in array. C program to find biggest and smallest elements in an array. Logic to find maximum and minimum element in array in C programming.

Example

Input

Input array elements: 10, 50, 12, 16, 2

Output

Maximum = 50
Minimum = 2

Required knowledge

Basic Input Output, If else, For loop, Array

Logic to find maximum and minimum element in array

Below is the step by step descriptive logic to find maximum or minimum in array.

  1. Input size and element in array, store it in some variable say size and arr.
  2. Declare two variables max and min to store maximum and minimum. Assume first array element as maximum and minimum both, say max = arr[0] and min = arr[0].
  3. Iterate through array to find maximum and minimum element in array. Run loop from first to last array element i.e. 0 to size - 1. Loop structure should look like for(i=0; i<size; i++).
  4. Inside loop for each array element check for maximum and minimum. Assign current array element to max, if (arr[i] > max). Assign current array element to min if it is less than min i.e. perform min = arr[i] if (arr[i] < min).

Program to find maximum and minimum element in array

/**
 * C program to find maximum and minimum element in array
 */

#include <stdio.h>

#define MAX_SIZE 100   // Maximum array size

int main()
{
    int arr[MAX_SIZE];
    int i, max, min, size;

    /* Input size of the array */
    printf("Enter size of the array: ");
    scanf("%d", &size);

    /* Input array elements */
    printf("Enter elements in the array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }


    /* Assume first element as maximum and minimum */
    max = arr[0];
    min = arr[0];

    /*
     * Find maximum and minimum in all array elements.
     */
    for(i=1; i<size; i++)
    {
        /* If current element is greater than max */
        if(arr[i] > max)
        {
            max = arr[i];
        }

        /* If current element is smaller than min */
        if(arr[i] < min)
        {
            min = arr[i];
        }
    }

    /* Print maximum and minimum element */
    printf("Maximum element = %d\n", max);
    printf("Minimum element = %d", min);

    return 0;
}

Add a plus to your skills, learn this program using recursive approach.

Output

Enter size of the array: 10
Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10
Maximum element = 100
Minimum element = -10

Happy coding 😉