C Arrays

An array in C stores multiple values of the same type under one name. Instead of creating many separate variables, you can keep related values together and access each value by its position.

Declaring An Array

To declare an array, write the type, the array name, and the number of elements in square brackets. For example, int scores[4]; creates an array that can hold four int values.

Array positions are called indexes. C arrays use zero-based indexing, so the first element is at index 0, the second is at index 1, and the last index is one less than the array length.

Initialize And Access Elements

You can give an array starting values with braces. Use an index in square brackets to read or change one element.

#include <stdio.h>

int main(void)
{
    int scores[4] = {90, 85, 78, 92};

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

    scores[2] = 80;
    printf("Updated third score: %d\n", scores[2]);

    return 0;
}

Output:

First score: 90
Last score: 92
Updated third score: 80

The array has four elements, so its valid indexes are 0, 1, 2, and 3. The assignment scores[2] = 80; changes only the third element.

Loop Through An Array

Arrays are often used with loops. A for loop is a good fit because indexes are numbers that move from the first element to the last.

#include <stdio.h>

int main(void)
{
    int temperatures[5] = {72, 75, 71, 69, 74};
    int i;

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

    return 0;
}

Output:

Day 1: 72
Day 2: 75
Day 3: 71
Day 4: 69
Day 5: 74

The loop starts at i = 0 because the first array element is index 0. It continues while i < 5, so the final index used is 4.

Use Arrays In Calculations

An array can also hold data that you combine into a result. This example adds all values and prints the average.

#include <stdio.h>

int main(void)
{
    int values[5] = {3, 7, 2, 9, 4};
    int total = 0;
    int i;

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

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

    return 0;
}

Output:

Total: 25
Average: 5.0

The expression values[i] means “the element at index i.” Each loop run adds one element to total. Dividing by 5.0 produces a decimal result.

Important Array Rules

  • All elements in one array have the same type.
  • The array size must be large enough for the number of elements you plan to store.
  • Valid indexes run from 0 to size - 1.
  • Accessing an index outside the array is a bug and can cause unpredictable behavior.
  • After declaration, you change individual elements such as scores[0], not the whole array with one assignment.

The key idea is that an array stores a fixed-size sequence of same-type values, and indexes let you access each value. Next, you will build on this with multidimensional arrays.