Skip to content
Lesson 4 of 13

Step 1 of 5 · Reading · ~4 min

Learn

Arrays and Strings

Arrays

An array is N values of one type stored side by side in memory, reached by number. By the end of this lesson you can declare one, fill it from input with a loop, and walk it while keeping track of something as you go.

Declaring and indexing

int ages[4] = {31, 7, 58, 19};   /* four ints, initialized */
int tally[6] = {0};              /* first is 0, the rest are zeroed too */
int raw[3];                      /* three slots of GARBAGE, like any uninitialized local */

ages[0]        /* 31: the first element is index 0 */
ages[3]        /* 19: the last element is index N-1 */
ages[1] = 8;   /* overwrite one slot */

ages[i] means "start of ages, plus i element-widths". That is why counting starts at 0: the first element sits at offset zero.

C has no bounds checking and arrays do not know their length. ages[7] compiles and runs; it reads whatever bytes happen to live there, and writing to it silently damages another variable. That is a buffer overflow. The length is yours to track, usually as a constant or with sizeof(ages) / sizeof(ages[0]) (total bytes divided by bytes per element, which gives 4).

Visiting every element: the for loop

The Loops lesson covers for in depth. For arrays you need one shape:

for (int i = 0; i < 4; i++) {
    printf("%d\n", ages[i]);
}

It has three parts: int i = 0 runs once; i < 4 is checked before every pass and the loop stops when it is false; i++ adds 1 after every pass. So i takes 0, 1, 2, 3, exactly the valid indices. Write i <= 4 and the loop also visits ages[4], one past the end, which C lets you do.

The same shape fills an array from input. scanf needs the address of the slot, so the argument is &ages[i], the same & you used for plain variables.

Deciding per element: if

Conditionals get a full lesson later. The minimum: if (condition) statement; runs the statement only when the condition is true. Comparisons are >, <, >=, <=, == (equal, two signs) and !=.

A worked example: tracking while you walk

One more shorthand appears below: total += x means total = total + x, and colder++ means colder = colder + 1.

This program reads four temperatures, then reports their total and how many were colder than the first reading:

#include <stdio.h>

int main(void) {
    int temps[4];
    for (int i = 0; i < 4; i++) scanf("%d", &temps[i]);

    int total = 0;              /* 0 is right for a sum: adding 0 changes nothing */
    int colder = 0;
    int first = temps[0];       /* the reference is a real reading, not a guess */

    for (int i = 0; i < 4; i++) {
        total += temps[i];
        if (temps[i] < first) colder++;
    }
    printf("%d %d\n", total, colder);
    return 0;
}

Input 12 9 15 4 gives the trace:

itemps[i]totalcolder
012120
19211
215361
34402

Output: 40 2. Every variable that carries a result across passes needs a starting value chosen on purpose. For a sum, 0 is neutral. For a comparison, a made-up number is a bug waiting for the right input; a value taken from the data is always fair.

Common mistakes

  • Starting a "largest so far" at 0. If every input is negative, nothing beats 0, so input -3 -1 -7 -9 -2 prints 0 instead of -1.
  • Stopping one short. A loop bound of i < 4 over five elements never looks at the last one, so 1 2 3 4 10 prints 4 instead of 10.
  • Flipping the comparison. Updating on < finds the smallest value: 4 1 7 3 5 prints 1 instead of 7.
  • Going one past the end. i <= 5 reads nums[5], which does not exist. The output depends on stray memory, so it may pass today and fail tomorrow.

Your exercise

Print the largest of five integers. The starter already reads them into nums and prints best; you give best a starting value from the array and write the loop that updates it. The likeliest slip is the first mistake above: a hidden test uses only negative numbers.

Up nextStringsArrays and Strings

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…