C program to find maximum and minimum element in array

Write a C program to enter elements in an array from user and find maximum and minimum elements in array. C program to find biggest and smallest elements in an array.

Example

Input

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

Output

Maximum = 50
Minimum = 2

Required knowledge

Basic C programming, For loop, Array

Must know - Program to find maximum between two numbers

Logic to find maximum/minimum in array

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

  1. Input element in array, store it in some variable say array.
  2. Declare a variable to store maximum. Assume first element of array as maximum, say max=array[0];.
  3. Run a loop from 0 to N-1, where N is the size of array. The loop structure should look like for(i=0; i<N; i++).
  4. Assign current array element to max variable, if(array[i] > max) then, max=array[i].

Program to find maximum or minimum element in array

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

#include <stdio.h>

int main()
{
    int arr[100];
    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];

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

        /* If current element of array 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;
}

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 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>