Skip to content

Part 1 · Lesson 8

Arrays

On this page

What you'll learn: arrays: declaring them, zero-based indexing, initializer lists, and looping over every element.

Before you start: Lessons 1-7, especially for loops from Lesson 6.

So far, we have only used variables that can hold one value at a time. For example, int score = 100;. But what if you need to store the scores for an entire class of 30 students? Declaring 30 separate variables (score1, score2, etc.) would be extremely inefficient.

An ARRAY is a data structure that can store a fixed-size, sequential collection of elements of the SAME data type. Think of it as a row of numbered boxes, where each box holds a value of the same type.

To declare an array, you specify the data type of its elements, the name of the array, and the number of elements it can hold (its size) in square brackets [].

The following line declares an array named high_scores that can hold exactly 5 integers:

int high_scores[5];

Accessing Array Elements

You access individual elements of an array using an INDEX in square brackets. C uses ZERO-BASED INDEXING. This is a critical concept. It means the first element is at index 0, the second at index 1, and so on. For an array of size 5, the valid indices are 0, 1, 2, 3, and 4.

high_scores[0] = 980; // the first element
high_scores[4] = 799; // the fifth (and last) element
printf("The highest score is: %d\n", high_scores[0]);

Accessing an index outside of this range (like high_scores[5]) leads to UNDEFINED BEHAVIOR, a common source of bugs and crashes in C programs.

Manually assigning each element is tedious. You can initialize an array when you declare it using an initializer list in curly braces {}.

If you provide an initializer list, you can let the compiler figure out the size of the array by leaving the square brackets empty:

double temperatures[] = {72.5, 75.0, 69.8, 80.1, 85.3}; // Size is 5
char grades[] = {'A', 'B', 'A', 'C', 'B', 'A'};         // Size is 6

The real power of arrays is realized when you combine them with loops. A for loop is perfect for iterating through an array, performing an action on each element. The loop counter doubles as the index:

for (int i = 0; i < 5; i++)
{
    printf("  Day %d: %.1f\n", i + 1, temperatures[i]);
}

i runs from 0 to 4, exactly the valid indices. Writing i <= 5 instead would read one element past the end.

Full Source

8_arrays.c 135 lines Download View on GitHub
/**
 * @file 8_arrays.c
 * @brief Part 1, Lesson 8: Arrays
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson introduces arrays, a fundamental data structure for storing
 * collections of elements of the same type.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * So far, we have only used variables that can hold one value at a time. For
 * example, `int score = 100;`. But what if you need to store the scores for
 * an entire class of 30 students? Declaring 30 separate variables (`score1`,
 * `score2`, etc.) would be extremely inefficient.
 *
 * An ARRAY is a data structure that can store a fixed-size, sequential
 * collection of elements of the SAME data type. Think of it as a row of
 * numbered boxes, where each box holds a value of the same type.
 */

#include <stdio.h>

int main(void)
{
    // --- Part 1: Declaring and Initializing an Array ---

    /*
     * To declare an array, you specify the data type of its elements, the name
     * of the array, and the number of elements it can hold (its size) in
     * square brackets `[]`.
     *
     * The following line declares an array named `high_scores` that can hold
     * exactly 5 integers.
     */
    int high_scores[5]; // An array of 5 integers.

    /*
     * ACCESSING ARRAY ELEMENTS:
     * You access individual elements of an array using an INDEX in square brackets.
     * C uses ZERO-BASED INDEXING. This is a critical concept. It means the
     * first element is at index 0, the second at index 1, and so on.
     * For an array of size 5, the valid indices are 0, 1, 2, 3, and 4.
     *
     * Accessing an index outside of this range (like `high_scores[5]`) leads to
     * UNDEFINED BEHAVIOR, a common source of bugs and crashes in C programs.
     */
    printf("--- Part 1: Assigning and Accessing Array Elements ---\n");
    high_scores[0] = 980; // Assign 980 to the first element
    high_scores[1] = 950; // Assign 950 to the second element
    high_scores[2] = 875;
    high_scores[3] = 820;
    high_scores[4] = 799; // The fifth (and last) element

    printf("The highest score is: %d\n", high_scores[0]);
    printf("The third highest score is: %d\n", high_scores[2]);
    printf("\n");

    // --- Part 2: Initializer Lists ---

    /*
     * Manually assigning each element is tedious. You can initialize an array
     * when you declare it using an initializer list in curly braces `{}`.
     *
     * If you provide an initializer list, you can let the compiler figure out
     * the size of the array by leaving the square brackets empty.
     */
    printf("--- Part 2: Using an Initializer List ---\n");
    double temperatures[] = {72.5, 75.0, 69.8, 80.1, 85.3}; // Size is 5
    char grades[] = {'A', 'B', 'A', 'C', 'B', 'A'};         // Size is 6

    printf("The first temperature recorded was: %.1f\n", temperatures[0]);
    printf("The fourth student's grade was: %c\n", grades[3]);
    printf("\n");

    // --- Part 3: Iterating Over an Array ---

    /*
     * The real power of arrays is realized when you combine them with loops.
     * A `for` loop is perfect for iterating through an array, performing an
     * action on each element.
     */
    printf("--- Part 3: Iterating Over an Array with a 'for' loop ---\n");
    printf("All recorded temperatures:\n");

    // We will loop from index 0 up to (but not including) 5.
    // The loop counter `i` is used as the array index.
    for (int i = 0; i < 5; i++)
    {
        printf("  Day %d: %.1f\n", i + 1, temperatures[i]);
    }
    printf("\n");

    // Let's use a loop to calculate the sum of all high scores.
    int total_score = 0;
    for (int i = 0; i < 5; i++)
    {
        total_score = total_score + high_scores[i];
    }
    printf("Sum of all high scores: %d\n", total_score);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you've learned to manage collections of data.
 *
 * Key Takeaways:
 * - An ARRAY is a fixed-size collection of elements of the same type.
 * - C uses ZERO-BASED INDEXING, where the first element is at index 0.
 * - Accessing an array element is done with `array_name[index]`.
 * - You can initialize an array with a list of values like `int arr[] = {1, 2, 3};`.
 * - Loops, especially `for` loops, are essential for processing each element in an array.
 *
 * NOTE: For now, we manually kept track of the array's size (e.g., `i < 5`). In
 * future lessons, we will learn more robust ways to handle array sizes.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the GCC compiler to create an executable file:
 *    `gcc -Wall -Wextra -std=c17 -o 8_arrays 8_arrays.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./8_arrays`
 *    - On Windows (WSL): `./8_arrays`
 */

How to Compile and Run

Runs the lesson in Compiler Explorer (GCC 16.2), nothing to install.

Once, before your first lesson

Install Apple's command line tools. They include the cc compiler: xcode-select --install

New to the terminal? The setup guide walks through it.

Build

$ cc -Wall -Wextra -std=c17 -o 8_arrays 8_arrays.c

Run

$ ./8_arrays

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Find and print the largest value in high_scores.
  2. Read 5 integers from the user into an array, then print them in reverse order.
  3. Compute the average of temperatures as a double and print it with one decimal place.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/08-arrays/ in the repository and on this lesson's page on the website.

Solutions

One worked solution for each exercise above, with the reasoning in its comments. They stay closed until you open them: have a go first, then compare.

Show the solution to exercise 1
1_largest_score.c 49 lines View on GitHub
/**
 * @file 1_largest_score.c
 * @brief Lesson 8, Exercise 1: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Find and print the largest value in `high_scores`.
 */

#include <stdio.h>

int main(void)
{
    // The lesson's scores happen to be sorted, which would hide a wrong
    // answer, so this solution uses the same five values in a mixed order.
    int high_scores[5] = {875, 980, 799, 950, 820};

    // "Best so far", as in Lesson 5, Exercise 3: assume the first element
    // is the largest, then let every other element challenge it.
    int largest = high_scores[0];

    // The loop can start at index 1, because index 0 is already in
    // `largest`. It stops before 5: the valid indices are 0 to 4.
    for (int i = 1; i < 5; i++)
    {
        if (high_scores[i] > largest)
        {
            largest = high_scores[i];
        }
    }

    printf("The largest score is: %d\n", largest); // 980

    return 0;
}

/*
 * WHY NOT START WITH `int largest = 0;`?
 *
 * It works for these scores, but it gives the wrong answer for an array of
 * negative numbers such as {-5, -2, -9}: nothing is greater than 0, so the
 * program would print 0, a value that is not in the array at all. Starting
 * from an element of the array is always right.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 1_largest_score 1_largest_score.c
 *   ./1_largest_score
 */
Show the solution to exercise 2
2_reverse_order.c 55 lines View on GitHub
/**
 * @file 2_reverse_order.c
 * @brief Lesson 8, Exercise 2: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Read 5 integers from the user into an array, then print them in reverse
 * order.
 */

#include <stdio.h>

int main(void)
{
    int numbers[5] = {0, 0, 0, 0, 0};

    // First loop: fill the array from index 0 up to index 4.
    for (int i = 0; i < 5; i++)
    {
        printf("Enter number %d of 5: ", i + 1);

        // An array element is a variable like any other, so `scanf` needs
        // its address: `&numbers[i]`.
        if (scanf("%d", &numbers[i]) != 1)
        {
            printf("That was not a whole number. Exiting.\n");
            return 1;
        }
    }

    // Second loop: walk the indices backwards, from 4 down to 0.
    // - It starts at 4, the LAST valid index, not at 5.
    // - It continues while `i >= 0`, so index 0 is included.
    printf("In reverse order:");
    for (int i = 4; i >= 0; i--)
    {
        printf(" %d", numbers[i]);
    }
    printf("\n");

    return 0;
}

/*
 * The array itself is not changed; only the order we visit it in is. Both
 * mistakes that are easy to make here are off-by-one errors: starting at
 * `numbers[5]` reads past the end of the array, and stopping at `i > 0`
 * silently skips the first number. Enter 1 2 3 4 5 and check that you see
 * 5 4 3 2 1, with both the 5 and the 1.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 2_reverse_order 2_reverse_order.c
 *   ./2_reverse_order
 */
Show the solution to exercise 3
3_average_temperature.c 49 lines View on GitHub
/**
 * @file 3_average_temperature.c
 * @brief Lesson 8, Exercise 3: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Compute the average of `temperatures` as a `double` and print it with one
 * decimal place.
 */

#include <stdio.h>

int main(void)
{
    double temperatures[] = {72.5, 75.0, 69.8, 80.1, 85.3}; // Size is 5

    // Add the elements up, exactly as the lesson sums `high_scores`. The
    // total is a `double` because the elements are.
    double total = 0.0;
    for (int i = 0; i < 5; i++)
    {
        total = total + temperatures[i];
    }

    // The average is the total divided by how many values there are.
    // `total` is a `double`, so this is floating-point division and the
    // fractional part is kept.
    double average = total / 5;

    printf("Total: %.1f\n", total);                 // 382.7
    printf("Average temperature: %.1f\n", average); // 76.5

    return 0;
}

/*
 * WATCH OUT WITH INTEGER ARRAYS
 *
 * Here the division is safe because `total` is a `double`. Do the same with
 * an `int` total, such as the lesson's `total_score`, and `total_score / 5`
 * is INTEGER DIVISION (Lesson 4): the fraction is thrown away before the
 * result is ever stored. For an average of integers, cast first:
 * `(double)total_score / 5`.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 3_average_temperature 3_average_temperature.c
 *   ./3_average_temperature
 */

Finished this lesson?

Mark it complete to track your progress through the course.

Search the course

Type at least two letters. Press / anywhere to search.

↑ ↓ to choose, Enter to open. On a lesson, j and k go to the next and previous lesson.