Reading Elements

Each element of an array has a position, called its index. Indexes are counted from zero: the first element has index 0, the second 1, the third 2, and so on. You can think of an index as the number of steps from the start of the array: the first element is right at the start, zero steps away.

int scores[] = {80, 92, 75, 60, 88};

This array has five elements, so its indexes go from 0 to 4. The last index is always one less than the size of the array: here 5 − 1 = 4. This is how the elements and their indexes line up:

         +----+----+----+----+----+
scores:  | 80 | 92 | 75 | 60 | 88 |
         +----+----+----+----+----+
index:      0    1    2    3    4

To read an element, write its index in square brackets after the array's name:

int scores[] = {80, 92, 75, 60, 88};
printf("%d\n", scores[0]);
printf("%d\n", scores[4]);

This prints:

80
88

An element of an array of int behaves just like an int variable. You can store it in another variable, calculate with it and print it with a label:

int scores[] = {80, 92, 75, 60, 88};
int first = scores[0];
printf("First: %d\n", first);
printf("First two together: %d\n", scores[0] + scores[1]);

This prints:

First: 80
First two together: 172

Watch out for the most common mistake: because counting starts at zero, the fifth element is scores[4], not scores[5]. Index 5 isn't part of this array at all. Later in this lesson, you'll see what happens when you use it.

Instructions

The array steps holds the number of steps you walked on each day of a week. Print the steps from Monday, the first day, with a label. The output should include the line Monday: 4200.

Print the steps from Sunday, the last day, the same way: Sunday: 3900. Think about which index the seventh element has.

Finally, print how many steps you walked over the weekend, on Saturday and Sunday together. Add the two elements up right in the printf; don't calculate the number yourself. The output should include the line Weekend: 15900.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/12