Arrays

An array is a fixed number of values of the same type, stored back-to-back in memory, and reached by position instead of by name.

Declaring and initializing an array

C main.c
#include <stdio.h>

int main(void) {
    int scores[5] = {88, 92, 79, 95, 84};

    printf("First score: %d\n", scores[0]);
    printf("Third score: %d\n", scores[2]);

    return 0;
}
Output
First score: 88
Third score: 79

int scores[5] declares an array of exactly 5 integers, sized once and fixed for its entire lifetime. Indexing starts at 0, not 1 — so scores[0] is the first element (88) and scores[2] is the third (79), not the second.

Note: C does not check array bounds for you. Reading or writing scores[5] or scores[100] compiles without complaint — it just reads or corrupts whatever memory happens to sit past the array, which is one of the most common sources of bugs and security vulnerabilities in C programs. There's no safety net here; keeping your own indices in range is entirely on you.

Iterating over an array

Arrays and for loops go together naturally — loop from 0 up to the array's length, using the loop variable as the index:

C main.c
#include <stdio.h>

int main(void) {
    int scores[5] = {88, 92, 79, 95, 84};
    int length = sizeof(scores) / sizeof(scores[0]);

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

    return 0;
}
Output
scores[0] = 88
scores[1] = 92
scores[2] = 79
scores[3] = 95
scores[4] = 84

sizeof(scores) gives the array's total size in bytes; sizeof(scores[0]) gives the size of a single element. Dividing one by the other gives the number of elements — a common trick for getting an array's length without hardcoding 5 somewhere it could get out of sync with the actual declaration.

Summing an array

Once you can loop over an array, running totals and averages fall out naturally:

C main.c
#include <stdio.h>

int main(void) {
    int scores[5] = {88, 92, 79, 95, 84};
    int total = 0;

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

    float average = total / 5.0;
    printf("Total: %d\n", total);
    printf("Average: %.1f\n", average);

    return 0;
}
Output
Total: 438
Average: 87.6

Dividing by 5.0 instead of plain 5 matters here — it forces the division to happen as floating-point math instead of truncating integer division, the same rule from the Operators lesson.