Using for loops for array traversal
What you'll learn: How to use a for loop to automatically visit and process every individual element in an array.
The Mailbox Analogy
Imagine a row of ten mailboxes at an apartment complex, numbered 0 through 9. If you are a mail carrier, you don't want to manually describe the action of opening every single box one by one in your head. Instead, you follow a simple mental rule: "Start at box 0, deliver the mail, and move to the next box until I finish box 9."
In C, a for loop acts as that mail carrier. Since arrays use numbers (indexes) to identify their compartments, the loop’s counter variable acts as the "finger" pointing to the current box you are opening.
Setting up the loop
To walk through an array, you need three things in your for loop:
- A starting point: Usually
int i = 0;(because arrays in C always start at index 0). - A stopping condition: The loop should run as long as
iis less than the size of the array. - A step:
i++to move to the next index after each turn.
Inside the loop, you access the current element using the syntax arrayName[i]. As i changes from 0 to 1 to 2, you effectively "touch" every item in the list.
Code Example: Summing a list
Here is how you would use a loop to look at every score in an integer array and calculate a total:
#include <stdio.h>
int main() {
int scores[5] = {85, 92, 78, 90, 88};
int total = 0;
// We loop from index 0 up to (but not including) 5
for (int i = 0; i < 5; i++) {
// Access the current element using the index 'i'
total += scores[i];
printf("Adding score at index %d: %d\n", i, scores[i]);
}
printf("The final total is: %d\n", total);
return 0;
}
Why this is powerful
By using a loop, your code stays the same length whether your array has five items or five thousand. You aren't just writing instructions for specific data; you are writing a "process" that can handle any amount of data. Whether you want to print every name in a list, find the highest number, or change every value to zero, the for loop is your primary tool for getting the job done.
Key takeaway
Use a for loop with a counter starting at 0 to visit every index of an array sequentially.