Arrays

Many values, one name

Suppose you want to store the marks of 5 students. Five separate variables (mark1, mark2, ...) would be clumsy. An array keeps them all together under one name:

#include <stdio.h>

int main() {
    int marks[5] = {80, 65, 92, 70, 88};
    printf("First mark: %d\n", marks[0]);
    printf("Third mark: %d\n", marks[2]);
    printf("Last mark: %d\n", marks[4]);
    return 0;
}

Output

First mark: 80
Third mark: 92
Last mark: 88
  • int marks[5] makes an array of 5 ints.
  • {80, 65, 92, 70, 88} are the starting values.
  • marks[0] is the first item. The number in square brackets is the index.

Think of it like this: An array is like a row of numbered lockers. Each locker holds one value, and you open a locker by its number.

Indexes start at 0

In C, the first item is at index 0, not 1. So an array of 5 items has the indexes 0, 1, 2, 3 and 4.

Common mistake: Using index 5 in an array of 5 items. marks[5] is outside the array. C does not stop you – it reads or overwrites some other memory, which causes strange bugs.

Changing an item

#include <stdio.h>

int main() {
    int marks[5] = {80, 65, 92, 70, 88};
    marks[1] = 75;          // change the second mark
    marks[4] += 2;          // add 2 to the last mark
    printf("%d %d\n", marks[1], marks[4]);
    return 0;
}

Output

75 90

Starting with zeros

If you give fewer values than the size, the rest are filled with 0. So {0} is an easy way to start with all zeros:

#include <stdio.h>

int main() {
    int counts[4] = {0};
    counts[2] = 7;
    printf("%d %d %d %d\n", counts[0], counts[1], counts[2], counts[3]);
    return 0;
}

Output

0 0 7 0

Remember: An array holds a fixed number of items of one type. Item positions start at 0 and end at size − 1.

HOME LABS COMMUNITY DASHBOARD