Lesson 5 of 8 · Functions and Arrays · 2 min read · Updated

Arrays: many values, one name

Hold a hundred numbers without declaring a hundred variables — and stay inside the bounds.

An array is a row of values of the same type, sitting next to each other in memory, under one name.

Five boxes side by side, counted from 0: marks[0] to marks[4].
c
#include <stdio.h>

int main(void)
{
    int marks[5] = {72, 85, 63, 91, 78};

    printf("First:  %d\n", marks[0]);
    printf("Fourth: %d\n", marks[3]);

    int total = 0;
    for (int i = 0; i < 5; i++) {
        total += marks[i];
    }

    printf("Average: %.1f\n", total / 5.0);
    return 0;
}
Output
First:  72
Fourth: 91
Average: 77.8

Warning

Counting starts at zero. In marks[5] the valid positions are 0, 1, 2, 3, 4 — there is no marks[5]. This catches everyone at least once.

C will not stop you going out of bounds

Reading marks[7] in a five-element array is not an error in C. It reads whatever happens to be in that memory — another variable, part of the program, anything. The result is nonsense, and writing there can corrupt your own data or crash the program.

Python raises an exception. C hands you whatever is there. This is the price of the speed, and the reason to be careful with loop bounds.

Strings are arrays of char

c
#include <stdio.h>
#include <string.h>

int main(void)
{
    char name[20] = "Priya";

    printf("%s\n", name);
    printf("Length: %d\n", (int) strlen(name));
    printf("First letter: %c\n", name[0]);

    return 0;
}

Note

A C string ends with a hidden \0 character, the null terminator. That is how functions know where the text stops. "Priya" needs six bytes, not five — always leave room for it.

In int marks[5];, which is the last valid index?

Try this now

  1. Read 5 numbers into an array and print the largest.
  2. Print an array backwards.
  3. Count how many numbers in an array are above the average.

Create a free account to save your progress, or sign in.