Course contentsShow
← C
Lesson 318 of 1,2194. Control FlowFree lesson

Finding Min and Max in a loop

Finding Min and Max in a loop

What you'll learn: How to track the smallest and largest values in a dataset by comparing each new entry against a running champion.

Imagine you are standing at the entrance of a building, and your job is to identify both the shortest and the tallest person who enters today. When the first person walks in, they are—by default—both the shortest and the tallest person you’ve seen so far. As every subsequent person enters, you compare their height to your current records. If someone is taller than your current "max," they become the new record holder. If someone is shorter than your "min," they take that spot.

In C, we use a loop to perform this comparison over and over again.

Initializing the Champions

A common mistake is to initialize your min or max variables to zero. However, if you are looking for the minimum value in a list of positive test scores and you start your min at 0, no score will ever be smaller than 0. Your program will wrongly report 0 as the minimum.

The safest strategy is to initialize your variables using the first piece of data you encounter. This ensures your "champions" are actual values from your dataset.

The Logic in Code

Here is how you track the highest and lowest numbers entered by a user:

#include <stdio.h>

int main() {
    int currentNum;
    int min, max;
    int i;

    printf("Enter number 1: ");
    scanf("%d", &currentNum);

    // Initialize both min and max to the very first number
    min = currentNum;
    max = currentNum;

    for (i = 2; i <= 5; i++) {
        printf("Enter number %d: ", i);
        scanf("%d", &currentNum);

        if (currentNum > max) {
            max = currentNum; // We found a new tallest!
        }
        
        if (currentNum < min) {
            min = currentNum; // We found a new shortest!
        }
    }

    printf("Smallest: %d\n", min);
    printf("Largest: %d\n", max);

    return 0;
}

How the Comparison Works

Inside the loop, the program acts like a filter. The if statements act as checkpoints. Notice that we use two separate if blocks rather than an if-else. This is because a single number could potentially be both the minimum and the maximum (which happens if all numbers entered are the same).

By the time the loop finishes, the variables min and max have "survived" every comparison, representing the extremes of the entire group.

Key takeaway: Always initialize min and max with the first element of your data to avoid reporting "ghost" values like zero.