← Back to C series
⚙️
Intermediate
1D · 2D · indexing

Chapter 3 — Arrays

A contiguous block of same-typed values. Indexed from 0. The foundation of strings, matrices, and most data structures.

arrayindex2D
Duration
1-2 hours
Level
📊 Beginner+
Prerequisite
🎯 Intermediate 2
Outcome
Declare and iterate arrays without OOB bugs

What you'll learn

  • 1Declare 1D and 2D arrays and access elements.
  • 2Iterate with `for` and `sizeof(arr)/sizeof(arr[0])`.
  • 3Pass arrays into functions (they decay to pointers).
  • 4Spot index out-of-range bugs.

Core Concepts

1) 1D array

c
int a[5] = {1, 2, 3, 4, 5};
printf("%d\n", a[0]);   // 1
printf("%d\n", a[4]);   // 5
// a[5] is OUT OF BOUNDS — undefined behavior

Indices run **0 to n-1**.

2) Length at compile time

c
int a[5];
size_t n = sizeof(a) / sizeof(a[0]);   // 5

This works only when `a` is the array itself, not a pointer. Once you pass it to a function it decays.

3) Iterate

c
for (size_t i = 0; i < n; i++) {
    printf("%d ", a[i]);
}

4) 2D array

c
int m[3][4];
m[1][2] = 42;

Stored **row-major**: rows are contiguous, columns are the inner index.

5) Partial initialization

c
int a[5] = {1, 2};   // a = {1, 2, 0, 0, 0}
int a[5] = {0};      // all zeros — common idiom

Examples

Example 1 — `ex01_basic.c`: declare + print

c
int a[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
    printf("a[%d]=%d\n", i, a[i]);
}

**Output**

text
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50

Key: index runs 0..4 for length 5.

Example 2 — `ex02_max.c`: find the maximum

c
int a[] = {3, 7, 1, 9, 4};
int n = sizeof(a) / sizeof(a[0]);
int max = a[0];
for (int i = 1; i < n; i++) {
    if (a[i] > max) max = a[i];
}
printf("max=%d\n", max);

**Output**

text
max=9

Key: start with `max = a[0]` and compare from index 1.

Example 3 — `ex03_reverse.c`: reverse in place

c
int a[] = {1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < n / 2; i++) {
    int t = a[i];
    a[i] = a[n - 1 - i];
    a[n - 1 - i] = t;
}
for (int i = 0; i < n; i++) printf("%d ", a[i]);

**Output**

text
5 4 3 2 1

Key: stop at `n/2`; otherwise you reverse twice.

Example 4 — `ex04_2d.c`: 2D matrix

c
int m[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        printf("%d ", m[i][j]);
    }
    printf("\n");
}

**Output**

text
1 2 3
4 5 6
7 8 9

Key: outer = rows, inner = columns.

Common mistakes

  1. **Index out of range** — most C bugs. The compiler doesn't check.
  2. **`sizeof` on a pointer** — gives 8, not array length.
  3. **Forgetting init** — uninitialized arrays hold garbage.
  4. **`array[0..=n]`** — there's no slice syntax in C.

Recap

  • Indices are 0-based; length minus one is the last valid index.
  • `sizeof` works on the array, not on a passed pointer.
  • 2D arrays are row-major.

Try it

bash
cd src
gcc -std=c11 -Wall -o ex01 ex01_basic.c && ./ex01
gcc -std=c11 -Wall -o ex02 ex02_max.c && ./ex02
gcc -std=c11 -Wall -o ex03 ex03_reverse.c && ./ex03
gcc -std=c11 -Wall -o ex04 ex04_2d.c && ./ex04

💻 Examples

Compilable, runnable examples — see the output yourself.

ex01_basic.cdeclare + print
CODE
#include <stdio.h>

int main(void) {
    int arr[5];

    for (int i = 0; i < 5; i++) {
        printf("arr[%d]: ", i);
        scanf("%d", &arr[i]);
    }

    printf("input: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    putchar('\n');
    return 0;
}
▶ Output
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
ex02_max.cfind the maximum
CODE
#include <stdio.h>

int main(void) {
    int arr[] = {12, 7, 38, 21, 9, 56, 3, 44};
    size_t n = sizeof(arr) / sizeof(arr[0]);

    int max = arr[0];
    int idx = 0;
    for (size_t i = 1; i < n; i++) {
        if (arr[i] > max) { max = arr[i]; idx = (int)i; }
    }

    printf("max: %d ( %d)\n", max, idx);
    return 0;
}
▶ Output
max=9
ex03_reverse.creverse in place
CODE
#include <stdio.h>

int main(void) {
    int arr[] = {1, 2, 3, 4, 5, 6, 7};
    size_t n = sizeof(arr) / sizeof(arr[0]);

    for (size_t i = 0; i < n / 2; i++) {
        int t = arr[i];
        arr[i] = arr[n - 1 - i];
        arr[n - 1 - i] = t;
    }

    printf("reversed: ");
    for (size_t i = 0; i < n; i++) printf("%d ", arr[i]);
    putchar('\n');
    return 0;
}
▶ Output
5 4 3 2 1
ex04_2d.c2D matrix
CODE
#include <stdio.h>

int main(void) {
    int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int B[2][3] = {{6, 5, 4}, {3, 2, 1}};
    int C[2][3];

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            C[i][j] = A[i][j] + B[i][j];

    printf("A + B =\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) printf("%3d ", C[i][j]);
        putchar('\n');
    }
    return 0;
}
▶ Output
1 2 3
4 5 6
7 8 9

📝 Exercises

Try them yourself first, then open the solution to compare.

Exercise 1

Problem 1 (hw01.c)

Goal: Read 5 ints; print sum and mean.

Requirements
  • Filename: hw01.c
Toggle solution
SOLUTION
#include <stdio.h>

int main(void) {
    int arr[10];
    int sum = 0;

    printf("Enter 10 ints: ");
    for (int i = 0; i < 10; i++) {
        scanf("%d", &arr[i]);
        sum += arr[i];
    }

    printf("sum: %d\n", sum);
    printf("mean: %.2f\n", sum / 10.0);
    return 0;
}
Exercise 2

Problem 2 (hw02.c)

Goal: Read N ints and print them in reverse order.

Requirements
  • Filename: hw02.c
Toggle solution
SOLUTION
#include <stdio.h>

int main(void) {
    int arr[] = {5, 3, 8, 1, 9, 2};
    int n = (int)(sizeof(arr) / sizeof(arr[0]));

    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                int t = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = t;
            }
        }
    }

    printf("sorted: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    putchar('\n');
    return 0;
}
Exercise 3

Problem 3 (hw03.c)

Goal: Print a `3x3` identity matrix.

Requirements
  • Filename: hw03.c
Toggle solution
SOLUTION
#include <stdio.h>

int main(void) {
    int A[3][3];
    int T[3][3];

    printf("3x3 matrix (9 ints):\n");
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            scanf("%d", &A[i][j]);

    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            T[j][i] = A[i][j];

    printf("transpose:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) printf("%4d", T[i][j]);
        putchar('\n');
    }
    return 0;
}
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗