Course contentsShow
← C
Lesson 400 of 1,2196. Arrays and StringsFree lesson

Printing array elements in a sequence

Printing array elements in a sequence

What you'll learn: How to use a for loop to visit and display every item stored in an array one by one.

The Post Office Analogy

Imagine a row of 5 mailboxes at a post office, numbered 0 to 4. If you want to check the mail in every box, you wouldn't just jump around randomly. You would start at box 0, look inside, move to box 1, look inside, and continue until you reach the end of the row.

In C, an array is that row of mailboxes. To "look inside" each one and print the value to the screen, we use a loop. Since we usually know exactly how many items are in an array, the for loop is our most reliable tool for this job.

Using the Loop

To iterate through an array, we create a counter variable (usually named i) that acts as our index. We start i at 0 because C arrays are zero-indexed. We tell the loop to keep running as long as i is less than the total size of the array. Each time the loop finishes one round, we increment i by 1 to move to the next "mailbox."

Here is how you print an array of five integers:

#include <stdio.h>

int main() {
    // An array of 5 high scores
    int scores[5] = {85, 92, 78, 99, 64};

    // We use 'i' to represent the current index
    for (int i = 0; i < 5; i++) {
        // Access the element at index 'i' and print it
        printf("Score at index %d is: %d\n", i, scores[i]);
    }

    return 0;
}

Why this works

In the code above, the first time the loop runs, i is 0, so the program executes scores[0]. The next time, i becomes 1, and the program executes scores[1].

Crucially, the condition i < 5 prevents the program from trying to access scores[5], which doesn't exist. If you try to go past the last index, the program might crash or print "garbage" data. By matching your loop's limit to the array's size, you ensure you touch every element exactly once.

Key takeaway

To print an array, use a for loop starting at index 0 and ending just before the array's total length.