C/C++ Arena

Step 3 of 7

Read into an array

Each element of an array is a normal variable, so you can read input directly into one. scanf needs its address, just like with a plain variable: &a[i].

A common pattern: first read how many values there will be, then read them into an array inside a loop.

#include <stdio.h>

int main(void) {
    int values[50];
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &values[i]);
    }
    int above = 0;
    for (int i = 0; i < n; i++) {
        if (values[i] > values[0]) {
            above++;
        }
    }
    printf("%d values are bigger than the first\n", above);
    return 0;
}
6
10 4 15 22 10 11
3 values are bigger than the first

Why store the values at all?

For a sum or a maximum you don't need an array: one pass while reading is enough. You need an array when you must look at the data more than once or out of order, like comparing everything to the first value, sorting, or printing in reverse. Reading first and processing afterwards is a very common program structure.

Capacity

The array has a fixed capacity (50 here). The program trusts the input to say at most 50. Real programs check that n fits before reading, or allocate memory of the right size at run time (you'll learn malloc in the dynamic memory module).

Looping backwards

To walk an array from the end, start at the last valid index and count down: for (int i = n - 1; i >= 0; i--). Note the start is n - 1, not n, and the condition is i >= 0 so index 0 is included.

Your turn: input is n (at most 100) followed by n numbers. Print them in reverse order on one line, separated by spaces.

Input 4 / 1 2 3 4 prints 4 3 2 1.

Previous: Loop over an array Next: Arrays as parameters