The Largest Value

The third pattern finds the largest value. Imagine going through a pile of exam papers to find the best one. You pick up the first paper. Then you look at the others one by one, and whenever one is better than the paper in your hand, you take that one instead. At the end, you're holding the best paper. In code, the paper in your hand is a variable:

int scores[] = {72, 45, 90, 38, 64};
int count = sizeof(scores) / sizeof(scores[0]);
int highest = scores[0];
for (int i = 1; i < count; i++) {
    if (scores[i] > highest) {
        highest = scores[i];
    }
}
printf("Highest score: %d\n", highest);

This prints:

Highest score: 90

The variable highest starts with the first element. That's why the loop can start at index 1: there's no need to compare the first element with itself (starting at 0 would work too). 45 is not greater than 72, but 90 is, so highest becomes 90. Neither 38 nor 64 is greater than 90, so 90 stays until the end.

Why not start with 0? Because 0 might not be one of the values. If all the values were negative, for example the winter temperatures {-5, -2, -8}, the starting 0 would stay the largest, and the program would print 0, a temperature that isn't in the array at all. The first element is always a safe start.

You find the smallest value the same way, only with < instead of >.

Sometimes you also need to know where the largest value is. Then keep its index in a second variable, and change both variables together:

int scores[] = {72, 45, 90, 38, 64};
int count = sizeof(scores) / sizeof(scores[0]);
int highest = scores[0];
int best_index = 0;
for (int i = 1; i < count; i++) {
    if (scores[i] > highest) {
        highest = scores[i];
        best_index = i;
    }
}
printf("Student %d has the most points: %d\n", best_index + 1, highest);

This prints:

Student 3 has the most points: 90

best_index starts at 0, the index of the first element, and changes whenever highest does. At the end, it's 2, so the student's number, counted from 1, is best_index + 1.

Instructions

The array prices holds the prices of headphones in an online shop. Create a variable highest of type int with the first price, prices[0].

Go through prices with a loop, and whenever a price is greater than highest, store it in highest. After the loop, print the result as Most expensive: 2499.

Find out which headphones they are. Create a variable highest_index with the value 0 next to highest, and in the loop, store the index i in it whenever you change highest. After the loop, print the number of the headphones, counted from 1, on the next line: Number: 4.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/12