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

Reading array values from user input

Reading array values from user input

What you'll learn: How to use a for loop to efficiently capture and store multiple pieces of data from a user into a single array.

The assembly line approach

Imagine you are a clerk at a warehouse with ten empty cubby holes. Ten people are standing in line, each holding a box. If you want to fill those cubbies, you wouldn't write a unique set of instructions for every single person. Instead, you would create a simple, repeating process: "Next person in line, put your box in the next empty hole."

In C, we use a for loop as this "assembly line" process. Because array indexes are just numbers that count up (0, 1, 2...), the loop's counter variable acts as the perfect guide to tell C exactly which "cubby" to fill next.

Using scanf with loops

To get data from a user, we use the scanf() function. When working with arrays, we place scanf() inside a loop. The key is to use the loop variable (usually i) inside the square brackets to target the specific index.

Here is how you fill an array of five integers:

#include <stdio.h>

int main() {
    int scores[5];
    int i;

    printf("Enter 5 game scores:\n");

    // The loop runs from index 0 to 4
    for(i = 0; i < 5; i++) {
        // We use &scores[i] to give scanf the address of the specific slot
        printf("Score %d: ", i + 1);
        scanf("%d", &scores[i]);
    }

    printf("Data saved successfully!");
    return 0;
}

Why the & symbol matters

When you use scanf, you aren't just telling C what you are looking for; you are telling it where to put it. The & symbol (the address-of operator) provides the memory address of a specific array element.

Think of scores[i] as the box itself, while &scores[i] is the GPS coordinate of that box. scanf needs that coordinate so it knows exactly which slot in the computer's memory to drop the user's input into. By the time the loop finishes its final lap, every "cubby" in your array is packed with data, ready to be used later in your program.

Key takeaway

To fill an array, use a for loop where the counter matches the array index, passing &arrayName[i] to scanf to store each input.