Kodewick
Lesson 11 of 30Contents

Arrays

Lesson 11 of 30 · Part 2 · Functions and arrays · about 15 minutes

A week has seven days. To keep how many steps you walked each day, do you need seven variables? No. An array is a row of variables of the same type that share one name and are numbered by position.

main.c
1#include <stdio.h>2 3int main(void) {4    int steps[7] = {4200, 6100, 5300, 8000, 7200, 9900, 3500};5    printf("Monday: %d steps\n", steps[0]);6    printf("Sunday: %d steps\n", steps[6]);7    return 0;8}
Output
Monday: 4200 steps
Sunday: 3500 steps

int steps[7] declares an array that holds 7 int values; the curly braces hold the values it starts with. Each value is an element, and the number in square brackets is its index. Press Step and you'll see the array drawn as a row of cells, each with its index under it.

Indexes start at 0

The first element has index 0, not 1. An array of 7 elements has indexes 0 to 6. steps[2] works just like an ordinary variable: you can read it and change it.

main.c
1#include <stdio.h>2 3int main(void) {4    int scores[3] = {78, 85, 90};5    printf("First: %d\n", scores[0]);6    scores[1] = 88;7    scores[2] += 5;8    printf("%d %d %d\n", scores[0], scores[1], scores[2]);9    return 0;10}
Output
First: 78
78 88 95

The index can also be a variable or an expression, like scores[i] or scores[i + 1]. That is what makes arrays useful.

Looping over an array

With a for loop where i goes from 0 to 4, you get each element in turn. Note that the condition is i < 5, not i <= 5.

main.c
1#include <stdio.h>2 3int main(void) {4    double temps[5] = {21.5, 23.0, 19.8, 25.2, 22.1};5    for (int i = 0; i < 5; i++) {6        printf("Day %d: %.1f degrees\n", i + 1, temps[i]);7    }8    return 0;9}
Output
Day 1: 21.5 degrees
Day 2: 23.0 degrees
Day 3: 19.8 degrees
Day 4: 25.2 degrees
Day 5: 22.1 degrees

printf can't print a whole array at once. You print it one element at a time, like this.

Sum and average

Start with 0 and add each element in the loop: that gives the total. Press Step and watch total grow.

main.c
1#include <stdio.h>2 3int main(void) {4    int steps[7] = {4200, 6100, 5300, 8000, 7200, 9900, 3500};5    int total = 0;6    for (int i = 0; i < 7; i++) {7        total += steps[i];8    }9    printf("Week: %d steps\n", total);10    printf("Daily average: %.1f steps\n", (double)total / 7);11    return 0;12}
Output
Week: 44200 steps
Daily average: 6314.3 steps

total is an int, and dividing it by 7 would drop the decimals, so it is converted with (double) first (lesson 4).

Finding the largest

Assume the first one is the largest, then compare from the second one on: whenever one is bigger, keep that one instead. Keep its index too, so you know which day it was.

main.c
1#include <stdio.h>2 3int main(void) {4    int steps[7] = {4200, 6100, 5300, 8000, 7200, 9900, 3500};5    int best = steps[0];6    int day = 0;7    for (int i = 1; i < 7; i++) {8        if (steps[i] > best) {9            best = steps[i];10            day = i;11        }12    }13    printf("The best day was day %d: %d steps\n", day + 1, best);14    return 0;15}
Output
The best day was day 6: 9900 steps

How big is an array?

The loops above have 7 written into them. Make the array 8 elements long and every 7 has to change too. sizeof can work it out: sizeof prices is the number of bytes the whole array takes, sizeof prices[0] is the bytes one element takes, and dividing them gives the number of elements.

main.c
1#include <stdio.h>2 3int main(void) {4    int prices[] = {12, 8, 25, 4};5    int count = sizeof prices / sizeof prices[0];6    printf("Whole array: %zu bytes\n", sizeof prices);7    printf("One element: %zu bytes\n", sizeof prices[0]);8    printf("Count: %d\n", count);9    return 0;10}
Output
Whole array: 16 bytes
One element: 4 bytes
Count: 4

Leave the size out of the square brackets and the compiler counts the values in the curly braces. Print a sizeof result with %zu.

If there are fewer values in the braces than the array has room for, the rest of the elements are 0:

Guess first

What does this print?

1#include <stdio.h>2 3int main(void) {4    int a[5] = {3, 1};5    printf("%d %d\n", a[1], a[4]);6    return 0;7}

If you write just int a[5]; with no braces, the elements are like variables you haven't assigned: nobody knows what's in them. Assign them before you use them.

Copying an array

You can't assign a whole array to another with =. To copy one, copy it element by element in a loop. After that the two arrays are separate: changing week2 doesn't touch week1.

main.c
1#include <stdio.h>2 3int main(void) {4    int week1[3] = {5, 7, 6};5    int week2[3];6    for (int i = 0; i < 3; i++) {7        week2[i] = week1[i];8    }9    week2[0] = 9;10    printf("%d %d\n", week1[0], week2[0]);11    return 0;12}
Output
5 9

Out of bounds

In an array of 5 elements, the last one is a[4]. Write i <= 5 and the loop reaches for a[5], a spot that isn't part of the array. C doesn't check this for you. A real program might read a garbage number, quietly change another variable, or crash: it is undefined behavior, and one of the most common bugs in C.

main.c
1#include <stdio.h>2 3int main(void) {4    int scores[5] = {78, 85, 90, 66, 72};5    int total = 0;6    for (int i = 0; i <= 5; i++) {7        total += scores[i];8    }9    printf("Total: %d\n", total);10    return 0;11}
Output
index 5 out of bounds for type 'int [5]'

What happened: Stopped at line 7. This goes past the end of an array (or a string). Real C would read or overwrite whatever is next in memory.

Our engine stops on the line where it happens and tells you which index was out of bounds. Press "see how it went wrong", or press Step to the end and watch the moment i becomes 5.

Tip: Write the loop condition as i < count, not i <= count. Work out the count with sizeof and it can't get out of step with the array.

Practice

Write the code, then press Check. A hint costs nothing; the answer is there when you need it.

Exercise 1

Lowest temperature

Find the lowest temperature in temps and print Lowest: -3.

It should print
Lowest: -3
exercise1.c
1#include <stdio.h>2 3int main(void) {4    int temps[6] = {4, -1, 2, -3, 0, 5};5 6    return 0;7}
Output
Press Run or Ctrl+Enter
Exercise 2

How many passed

Count how many scores in scores are 60 or more, and print Passed: 4. Use sizeof to get the number of elements.

It should print
Passed: 4
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int scores[] = {58, 72, 91, 45, 60, 83};5 6    return 0;7}
Output
Press Run or Ctrl+Enter
Exercise 3

Backwards

Fix this loop so it prints the elements from the last one back to the first, one per line. Right now it goes out of bounds.

It should print
5
4
3
2
1
exercise3.c
1#include <stdio.h>2 3int main(void) {4    int a[5] = {1, 2, 3, 4, 5};5    for (int i = 5; i >= 0; i--) {6        printf("%d\n", a[i]);7    }8    return 0;9}
Output
Press Run or Ctrl+Enter

What you learned

  • An array is a row of elements of one type: int a[5] = {...};. Leave out the size and it's the number of values in the braces.
  • Indexes start at 0: an array of n elements has indexes 0 to n - 1.
  • Loop over it with for (int i = 0; i < n; i++) to add up, average, or find the largest and smallest.
  • sizeof a / sizeof a[0] is the number of elements; values you don't give are 0.
  • You can't copy a whole array with =; copy it element by element in a loop.
  • Going out of bounds is undefined behavior, and C doesn't check it for you. Write the condition as i < n.