C Language track

Lesson 07 · Level 2: Intermediate

Arrays

Declaring, initialising and accessing arrays, including multidimensional arrays

Level 2: Intermediate4 min readFree lesson

An array is a tool that handles values of the same data type as a bundle. Instead of creating 100 separate variables, you can process them as one 100-space array.

Learning Objectives

  • Declare, initialize, and index the 1-dimensional/2-dimensional array.
  • Find the array length using the sizeof trick.
  • Understand through pictures how the array is arranged in memory.
  • Know the risk of index range errors.

Why do you need an array?

If we treat the scores of 5 students as 5 variables:

int s1=90, s2=85, s3=78, s4=92, s5=88;   //The same process must be repeated 5 times

Converting it to an array:

int score[5] = {90, 85, 78, 92, 88};
for (int i = 0; i < 5; i++) printf("%d\n", score[i]);

Even if the number of students increases to 100, the code remains virtually the same.

Key concepts

1) Declaration and initialization

int a[5];                    //garbage price
int b[5] = {1, 2, 3};        //Fill the rest with 0
int c[]  = {10, 20, 30};     //Size determined by compiler (3)

2) Arrays in memory are “contiguous columns”

int arr[5] = {10, 20, 30, 40, 50};

Address: 0x100 0x104 0x108 0x10c 0x110
        ┌─────┬─────┬─────┬─────┬─────┐
        │ 10  │ 20  │ 30  │ 40  │ 50  │
        └─────┴─────┴─────┴─────┴─────┘
Index: [0] [1] [2] [3] [4]

Each cell is spaced sizeof(int) bytes apart. Index starts from 0. The last index is Length - 1.

3) Calculate length — sizeof trick

int arr[10];
size_t n = sizeof(arr) / sizeof(arr[0]);   // 10

Divide the total number of bytes by the number of bytes per space. Caution: This does not work with arrays received as function parameters (they are converted to pointers and size information is lost).

4) Two-dimensional array (matrix)

int grid[3][4];     //3 rows 4 columns
grid[i][j] = i * 4 + j;
grid[0]: ┌────┬────┬────┬────┐
        │ 0  │ 1  │ 2  │ 3  │
grid[1]: ├────┼────┼────┼────┤
        │ 4  │ 5  │ 6  │ 7  │
grid[2]: ├────┼────┼────┼────┤
        │ 8  │ 9  │ 10 │ 11 │
        └────┴────┴────┴────┘

C stores things in memory row-major (one line must end before the next).

See as example

Example 1 — ex01_basic.c: Input and Output

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

Input: 10 20 30 40 50

arr[0] input: arr[1] input: arr[2] input: arr[3] input: arr[4] input: input value: 10 20 30 40 50

Key point: Like &arr[i], we pass addresses of individual elements to scanf.

Example 2 — ex02_max.c: Finding the maximum value

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

Execution result

Maximum: 56 (index 5)

Key point: “Take the first element as a temporary answer and compare the rest” is the standard pattern.

Example 3 — ex03_reverse.c: Flipping an array

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

Execution result

Flipped result: 7 6 5 4 3 2 1

Key point: swap inwards from both ends. n/2 repetitions are sufficient.

Example 4 — ex04_2d.c: Two-dimensional array sum

int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[2][3] = {{6, 5, 4}, {3, 2, 1}};
for (i...) for (j...) C[i][j] = A[i][j] + B[i][j];

Execution result

A + B =
  7   7   7
  7   7   7

Key point: traversing a matrix with a double for. Don't forget \n in each line when printing.

A different perspective — arr[i] is actually *(arr + i)

In C grammar, arr[i] is automatically converted to *(arr + i) by the compiler. That is, the array name behaves like the address of the first element (see the Pointers section for more information).

   arr ─►  ┌────┬────┬────┬────┬────┐
           │ 10 │ 20 │ 30 │ 40 │ 50 │
           └────┴────┴────┴────┴────┘
              i=0   i=1   i=2   ...
arr + 2 ──────────► (This address is the address of arr[2])

Common Mistakes

  1. Index Overrun: int a[5]; a[5] = 0; → Undefined operation.
  2. Loop condition inequality mistake: Approach one more space with for (i = 0; i <= n; i++).
  3. sizeof(arr) / sizeof(arr[0]) in the function: always becomes pointer/element in the parameter, which is broken.
  4. 2D array row/column confusion: In arr[i][j], i is the row, j is the column.
  5. Depends on Variable Length Array (VLA): int a[n]; is possible with C99 variable array, but large n risks stack overflow.

Cleanup

  • An array is a group of values of the same data type placed consecutively in memory.
  • The index starts from 0, and the last one is Length - 1.
  • sizeof(arr) / sizeof(arr[0]) is only valid for local arrays.
  • Two-dimensional arrays are accessed in [row][column] order and stored in row priority.
  • Since the compiler does not check the index range, the developer is responsible.

Try it yourself

cd src
gcc -std=c11 -Wall -o ex01 ex01_basic.c   && echo "10 20 30 40 50" | ./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

Application:

  • Try extending it to also find the minimum in ex02.
  • Try changing ex04 to a 5x5 matrix and output the identity matrix (1 on the diagonal only).

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/ex01_basic.cC
#include <stdio.h>

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

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

    printf("Input values:");
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    putchar('\n');
    return 0;
}
src/ex02_max.cC
#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("Maximum value: %d (index %d)\n", max, idx);
    return 0;
}
src/ex03_reverse.cC
#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("Flipped result:");
    for (size_t i = 0; i < n; i++) printf("%d ", arr[i]);
    putchar('\n');
    return 0;
}
src/ex04_2d.cC
#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;
}

Assignment

Problem 1

Input 10 integers and output the sum and average (2 decimal places).

  • File name: hw01.c

Problem 2

Sort the array {5, 3, 8, 1, 9, 2} in ascending order using bubble sort and print it.

  • File name: hw02.c

Problem 3

Take int A[3][3] as input and output the transpose matrix.

  • File name: hw03.c
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

hw01.cC
#include <stdio.h>

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

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

    printf("Total: %d\n", sum);
    printf("Average: %.2f\n", sum / 10.0);
    return 0;
}
hw02.cC
#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("Sort results:");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    putchar('\n');
    return 0;
}
hw03.cC
#include <stdio.h>

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

    printf("3x3 matrix input (9 in total):\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 matrix:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) printf("%4d", T[i][j]);
        putchar('\n');
    }
    return 0;
}

Learn this lesson with a mentor

Work through the C Language track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now