Find Maximum and Minimum in an Array in C

Finding the maximum and minimum elements in an array is one of the most basic and important problems in programming.

It helps in understanding array traversal and comparison logic.

In this tutorial, we will implement efficient methods in C.

Concept Overview

We traverse the array once and compare each element with current max and min values.

This avoids unnecessary repeated comparisons.

Problem Statement

Given an array, find the largest and smallest elements.

Example

TEXT
Input:
Array: 5 2 9 1 7

Output:
Maximum: 9
Minimum: 1

Approach

1. Initialize max and min with the first element.

2. Traverse the array from index 1.

3. If current element > max, update max.

4. If current element < min, update min.

5. Continue until end of array.

C Program

C
#include <stdio.h>

int main() {
    int arr[] = {5, 2, 9, 1, 7};
    int n = sizeof(arr) / sizeof(arr[0]);

    int max = arr[0];
    int min = arr[0];

    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
        if (arr[i] < min) {
            min = arr[i];
        }
    }

    printf("Maximum: %d\n", max);
    printf("Minimum: %d", min);

    return 0;
}

Output

TEXT
Maximum: 9
Minimum: 1

Detailed Explanation

The program initializes max and min with the first element of the array.

Then it iterates through the remaining elements and updates values accordingly.

This ensures we find both values in a single pass.

Time and Space Complexity

Time Complexity: O(n)

Space Complexity: O(1)

Optimized Approach (Reduced Comparisons)

We can reduce the number of comparisons by processing elements in pairs.

C
#include <stdio.h>

int main() {
    int arr[] = {5, 2, 9, 1, 7, 3};
    int n = sizeof(arr) / sizeof(arr[0]);

    int max, min;
    int i;

    if (arr[0] > arr[1]) {
        max = arr[0];
        min = arr[1];
    } else {
        max = arr[1];
        min = arr[0];
    }

    for (i = 2; i < n; i += 2) {
        if (i + 1 < n) {
            if (arr[i] > arr[i + 1]) {
                if (arr[i] > max) max = arr[i];
                if (arr[i + 1] < min) min = arr[i + 1];
            } else {
                if (arr[i + 1] > max) max = arr[i + 1];
                if (arr[i] < min) min = arr[i];
            }
        } else {
            if (arr[i] > max) max = arr[i];
            if (arr[i] < min) min = arr[i];
        }
    }

    printf("Maximum: %d\n", max);
    printf("Minimum: %d", min);

    return 0;
}

Applications

Used in data analysis and statistics.

Helps in optimization problems and searching algorithms.

Advantages

Simple and efficient solution.

Works in a single traversal.

Limitations

Requires at least one element in array.

Improvements You Can Make

Handle user input dynamically.

Extend program to find second largest and smallest elements.

Apply same logic to multi-dimensional arrays.

This is a foundational problem that builds your understanding of array processing in C.