Finding the maximum value in an array
What you'll learn: How to use a loop and a tracker variable to identify the largest number stored in a list.
The logic of the "King of the Hill"
Imagine you have a stack of cards, each with a different number on it. To find the highest number, you don't need to look at all the cards at once. Instead, you pick up the first card and say, "For now, this is the highest I’ve seen." Then, you flip the next card. If it’s bigger than your current highest, you swap them in your mind. If it’s smaller, you ignore it and move on. By the time you reach the bottom of the stack, the number you are holding is guaranteed to be the maximum.
In C, we replicate this by using a loop to visit every index in an array and a "tracker" variable to store the current winner.
Implementing the search
To do this in code, we initialize a variable (often called max) with the very first element of the array. We then use a for loop to compare this variable against every other element.
#include <stdio.h>
int main() {
int scores[] = {45, 82, 19, 94, 67};
int length = 5;
// 1. Assume the first element is the largest
int max = scores[0];
// 2. Iterate through the rest of the array
for (int i = 1; i < length; i++) {
// 3. If we find something bigger, update max
if (scores[i] > max) {
max = scores[i];
}
}
printf("The highest score is: %d\n", max);
return 0;
}
Why start at index 0?
A common mistake is initializing your max variable to 0. However, if your array contains only negative numbers (like temperatures in the Arctic), 0 would incorrectly remain the maximum because it's larger than any of the data points. By starting max as scores[0], you ensure your starting point is an actual value from your dataset.
As the loop runs, the if statement acts as a filter. Each time the loop encounters a value that "beats" the current max, the old value is discarded and replaced. Once the loop finishes its journey through the memory, max holds the ultimate champion.
Key takeaway
To find the maximum, assume the first element is the largest, then loop through the array and update your "max" variable whenever you find a larger value.