SyntaxPilot
Courses/C Programming/Lesson 8

C Programming · Lesson 8 of 30 · 11 min

Arrays

queued

These are the notes for C episode 8. In episode 6 our loop added up the day's bills, but each bill was forgotten the moment it was added. Here you invent a way to keep every value under one name: the array. You will learn how to declare and initialise an array, why indexes start at 0, how to loop over an array, what happens when you go one slot too far (out of bounds and undefined behavior), how sizeof counts the slots, how partial initialisation fills zeros, how to read an array with scanf, why one array can't be assigned to another, how arrays are passed to functions (and the sizeof trap there), and 2D arrays for tables. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.

The problem: keeping every bill of the day

Bhaiya's chai stall makes bills all day: 120, 45, 80, 200, 60 and so on. Our running total from episode 6 gives the day's total, but at night bhaiya asks: what was the third bill? Which bill was the biggest? We can't answer, because each bill was thrown away after it was added.

The obvious way: one variable per bill, and a loop that tries to add bill1, bill2, bill3 by writing bill + i:

#include <stdio.h>

int main() {
    int bill1 = 120, bill2 = 45, bill3 = 80;
    int total = 0;
    for (int i = 1; i <= 3; i++) {
        total = total + bill + i;
    }
    printf("Total: %d\n", total);
    return 0;
}

gcc says:

main.c: In function 'main':
main.c:7:25: error: 'bill' undeclared (first use in this function); did you mean 'bill3'?
    7 |         total = total + bill + i;
      |                         ^~~~
      |                         bill3
main.c:7:25: note: each undeclared identifier is reported only once for each function it appears in

To C, bill + i means "a variable called bill, plus i". It cannot glue a number onto a name. And even if it could, 1,000 bills would mean 1,000 variables typed by hand.

Why it failed

  • Variable names are fixed when you write the code.
  • A loop has a number (i) that changes, but C cannot turn a number into a name.
  • What we want: one name for all the bills, plus a slot number that a loop can change.

The fix: an array

Real-life example: a train with numbered coaches.

At the station In C
One train name (Rajdhani Express) One array name: int bills[5];
Every coach is the same kind Every slot holds an int, side by side in memory
"Go to coach 2" bills[2]: the index picks a slot
The first coach is 0 steps from the engine The first slot is bills[0]

An array is one name for a fixed number of values of the same type, stored side by side. Each value is an element; the number in square brackets that picks an element is its index. C counts how far a slot is from the start, so the first element is at index 0, and an array of 5 has indexes 0 to 4.

#include <stdio.h>

int main() {
    int bills[5] = {120, 45, 80, 200, 60};
    printf("First bill: %d\n", bills[0]);
    printf("Third bill: %d\n", bills[2]);
    int total = 0;
    for (int i = 0; i < 5; i++) {
        total = total + bills[i];
    }
    printf("Total: %d\n", total);
    return 0;
}

Output:

First bill: 120
Third bill: 80
Total: 505

Every bill is kept, and the loop reaches each one by number: bills[i] is a different slot on every pass. You just invented arrays.

Anatomy of an array

int bills[5] = {120, 45, 80, 200, 60};
  1. Type int: every slot holds an int.
  2. Name bills.
  3. Size [5]: five slots. An array's size is fixed forever once it is created.
  4. Initialiser { ... }: the values fill slots 0, 1, 2, 3, 4 in order.
Index 0 1 2 3 4
Value 120 45 80 200 60

Rule: the last index is always size − 1.

One coach too far: out of bounds

The train has coaches 0 to 4. What if the loop says i <= 5?

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

gcc warns:

main.c: In function 'main':
main.c:9:30: warning: iteration 5 invokes undefined behavior [-Waggressive-loop-optimizations]
    9 |         total = total + bills[i];
      |                         ~~~~~^~~
main.c:8:23: note: within this loop
    8 |     for (int i = 0; i <= 5; i++) {
      |                     ~~^~~~

But it still compiles and runs:

First bill: 120
Third bill: 80
Total: 33269

The total is a big wrong number (the exact value changes from run to run). The loop read bills[5], a slot that doesn't exist. That is out of bounds access, and in C it is undefined behavior: the language makes no promise at all. You might get a wrong number, a crash, or a program that seems fine today and breaks tomorrow.

Peeking directly:

#include <stdio.h>

int main() {
    int bills[5] = {120, 45, 80, 200, 60};
    printf("bills[5]   = %d\n", bills[5]);
    printf("bills[100] = %d\n", bills[100]);
    return 0;
}

One run printed:

bills[5]   = 32766
bills[100] = -819128385

Both are junk read from memory that belongs to something else, and the numbers change on every run. There is no error: C never checks the index for you. Always loop with i < size, never i <= size.

sizeof and initialising

Typing 5 everywhere is the copy-paste problem from episode 7 again: change the size in one place, forget another. sizeof gives the number of bytes something takes, so it can count the slots:

#include <stdio.h>

int main() {
    int bills[5];
    int count = sizeof(bills) / sizeof(bills[0]);
    printf("sizeof(bills): %zu bytes\n", sizeof(bills));
    printf("Count: %d\n", count);
    int stock[5] = {10, 20};
    for (int i = 0; i < 5; i++) printf("%d ", stock[i]);
    printf("\n");
    return 0;
}

Output:

sizeof(bills): 20 bytes
Count: 5
10 20 0 0 0 
  • sizeof(bills) is 20 bytes (5 ints × 4 bytes); sizeof(bills[0]) is 4. 20 / 4 = 5 slots. %zu is the format specifier for sizeof results.
  • Partial initialisation: if you give fewer values than slots, C fills the rest with 0. So int bills[5] = {0}; sets every slot to 0.
  • No initialiser at all (int bills[5]; inside a function): the slots hold garbage values, whatever was left in memory.

You can also leave the size out and let C count the initialiser: int bills[] = {120, 45, 80}; makes an array of 3.

Copying an array

With ints, a = b copies a value. With arrays:

#include <stdio.h>

int main() {
    int today[3] = {120, 45, 80};
    int copy[3];
    copy = today;
    return 0;
}
main.c: In function 'main':
main.c:6:10: error: assignment to expression with array type
    6 |     copy = today;
      |          ^

A whole array can't be assigned with one =. Copy it slot by slot:

#include <stdio.h>

int main() {
    int today[3] = {120, 45, 80};
    int copy[3];
    for (int i = 0; i < 3; i++) {
        copy[i] = today[i];
    }
    printf("%d %d %d\n", copy[0], copy[1], copy[2]);
    return 0;
}

Output:

120 45 80

Arrays in functions

Let's move the total into a function and count the slots with sizeof inside it:

#include <stdio.h>

int total(int bills[]) {
    int n = sizeof(bills) / sizeof(bills[0]);
    int sum = 0;
    for (int i = 0; i < n; i++) sum += bills[i];
    return sum;
}

int main() {
    int bills[5] = {120, 45, 80, 200, 60};
    printf("Total: %d\n", total(bills));
    return 0;
}

gcc warns:

main.c: In function 'total':
main.c:4:19: warning: 'sizeof' on array function parameter 'bills' will return size of 'int *' [-Wsizeof-array-argument]
    4 |     int n = sizeof(bills) / sizeof(bills[0]);
      |                   ^
main.c:3:15: note: declared here
    3 | int total(int bills[]) {
      |           ~~~~^~~~~~~

Output:

Total: 165

Only the first two bills (120 + 45) were added. Inside the function, bills is not the whole array: it is only the address where the array starts (an int *, 8 bytes on a 64-bit machine). 8 / 4 = 2, so the loop ran twice.

Real-life example: telling a friend about the train. You don't build them a copy of the train; you say "it's on platform 3" (where it starts). They don't know how long it is, so you also say "it has 5 coaches" (pass the size). And they walk onto the real train, so any change they make is real.

#include <stdio.h>

int total(int bills[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) sum += bills[i];
    return sum;
}

void add_tip(int bills[], int n) {
    for (int i = 0; i < n; i++) bills[i] += 10;
}

int main() {
    int bills[5] = {120, 45, 80, 200, 60};
    printf("Total: %d\n", total(bills, 5));
    add_tip(bills, 5);
    printf("After tip: %d\n", total(bills, 5));
    return 0;
}

Output:

Total: 505
After tip: 555
  • Always pass the size along with the array.
  • Unlike the photocopy of an int in episode 7, a function can change the caller's array, because it works on the original through its address. Exactly why is the topic of episode 10 (pointers).

2D arrays: the weekly sales register

Bhaiya wants a register: how many of each item sold on each day. That's a table: rows for items (chai, samosa, lassi), columns for days.

At the register In C
Rows = items sales[3][...]: 3 rows
Columns = days sales[...][4]: 4 columns
"Samosa, day 3" sales[1][2]: row 1, column 2 (both from 0)

A 2D array is an array of arrays: int sales[3][4] is 3 rows, each an array of 4 ints. Read a cell with [row][column].

#include <stdio.h>

int main() {
    int sales[3][4] = {
        {20, 25, 30, 40},
        {10, 12, 15, 18},
        { 5,  8,  6,  9}
    };
    printf("Samosa, day 3: %d\n", sales[1][2]);
    for (int r = 0; r < 3; r++) {
        int sum = 0;
        for (int d = 0; d < 4; d++) {
            sum = sum + sales[r][d];
        }
        printf("Item %d total: %d\n", r, sum);
    }
    return 0;
}

Output:

Samosa, day 3: 15
Item 0 total: 115
Item 1 total: 55
Item 2 total: 28

A nested loop (like the cinema seats in episode 6): the outer loop picks a row, the inner loop walks across its columns.

Common mistakes (and the real gcc messages)

Mistake What you see Why Fix
for (i = 0; i <= 5; i++) bills[i] warning: iteration 5 invokes undefined behavior, then a wrong total, no error Indexes are 0 to size − 1 i < 5
copy = today; error: assignment to expression with array type Arrays can't be assigned whole Copy slot by slot in a loop
sizeof(bills) inside a function warning: 'sizeof' on array function parameter 'bills' will return size of 'int *', wrong count The function only gets the start address Pass the size: total(bills, 5)
int bills[5]; then print it No error, garbage values Not initialised int bills[5] = {0};
bills[5] or bills[100] No error, junk numbers that change every run Out of bounds: C never checks Keep every index in 0 … size − 1
bill + i to reach bill1, bill2 error: 'bill' undeclared … did you mean 'bill3'? A loop can't build a variable name Use an array: bills[i]

Mini project: a week of chai sales

Read 7 days of sales, then print the week's total, the daily average and the best day.

#include <stdio.h>

int main() {
    int sales[7];
    for (int i = 0; i < 7; i++) {
        scanf("%d", &sales[i]);
    }
    int total = 0, best = 0;
    for (int i = 0; i < 7; i++) {
        total = total + sales[i];
        if (sales[i] > sales[best]) best = i;
    }
    printf("Week total: %d cups\n", total);
    printf("Average: %.1f cups a day\n", total / 7.0);
    printf("Best day: day %d (%d cups)\n", best + 1, sales[best]);
    return 0;
}

Input:

120 95 140 110 160 210 180

Output:

Week total: 1015 cups
Average: 145.0 cups a day
Best day: day 6 (210 cups)
  • scanf needs the address of each slot: &sales[i].
  • best stores the index of the best day so far, not the value, so we can print both the day and the cups.
  • total / 7.0 divides by a double, so the average keeps its decimals (episode 3's integer-division trap).
  • best + 1 because humans count days from 1.

Practice

  1. Read 5 marks and print the highest and lowest.
  2. Print an array in reverse order.
  3. Count how many bills are above 100.
  4. Add a 4th item row to the sales table and print its total.
  5. Add the worst day to the mini project.
Solutions and hints

Exercises 1–3 in one program (verified, input 78 92 65 88 71):

#include <stdio.h>

int main() {
    int marks[5];
    for (int i = 0; i < 5; i++) {
        scanf("%d", &marks[i]);
    }
    int high = marks[0], low = marks[0];
    for (int i = 1; i < 5; i++) {
        if (marks[i] > high) high = marks[i];
        if (marks[i] < low) low = marks[i];
    }
    printf("Highest: %d\n", high);
    printf("Lowest: %d\n", low);

    int bills[6] = {120, 45, 80, 200, 60, 150};
    int n = sizeof(bills) / sizeof(bills[0]);
    printf("Reversed:");
    for (int i = n - 1; i >= 0; i--) {
        printf(" %d", bills[i]);
    }
    printf("\n");

    int count = 0;
    for (int i = 0; i < n; i++) {
        if (bills[i] > 100) count++;
    }
    printf("Bills above 100: %d\n", count);
    return 0;
}

Output:

Highest: 92
Lowest: 65
Reversed: 150 60 200 80 45 120
Bills above 100: 3

Start high and low at the first element, not at 0: if all marks were negative, starting at 0 would give a wrong highest.

4. Make the table int sales[4][4], add a row such as {15, 14, 20, 22}, and loop r < 4. The new line of output is Item 3 total: 71.

5. Add int worst = 0; and, in the same loop, if (sales[i] < sales[worst]) worst = i;. With the sample input the worst day is day 2 (95 cups).

Quick quiz

What does this print?

int a[5] = {4, 8};
int s = 0;
for (int i = 0; i < 5; i++)
    s = s + a[i];
printf("%d %d", a[4], s);
  • A. 0 12
  • B. 8 12
  • C. Garbage, then 12
  • D. Error
Answer

A: 0 12. Only two values were given, so C fills the other three slots with zeros: a is {4, 8, 0, 0, 0}. a[4] is 0 and the sum is 4 + 8 = 12.

Interview questions

  • Why do array indexes start at 0 in C?
  • What happens if you access an array out of bounds? Does C check it?
  • What is undefined behavior?
  • How do you find the number of elements in an array? Why doesn't that work inside a function?
  • What values does int a[5] = {1}; contain? And int a[5]; inside a function?
  • Why can't you write b = a; for two arrays? How do you copy one?
  • When you pass an array to a function, is it copied? Can the function change it?
  • How is a 2D array stored, and how do you access a[i][j]?
  • Can an array's size change after it is created? (No; for that, see dynamic memory in episode 14.)

Glossary

Term Meaning Example
Array One name for a fixed number of values of the same type, stored side by side int bills[5];
Element One value stored in an array bills[2] holds 80
Index The slot number in square brackets, counted from 0 the 2 in bills[2]
Size (length) How many elements the array has; fixed when it is created 5 in int bills[5]
Initialiser The { ... } list of starting values {120, 45, 80, 200, 60}
Initialising Giving values at the moment the array is created int a[3] = {1, 2, 3};
Partial initialisation Fewer values than slots: the rest become 0 int stock[5] = {10, 20}; → 10 20 0 0 0
Garbage value Leftover junk in memory that was never set int bills[5]; printed without values
Out of bounds Using an index below 0 or ≥ the size bills[5] in a 5-element array
Undefined behavior Code whose result C does not define: any outcome is possible reading bills[5]
sizeof Gives the size in bytes of a type, variable or array sizeof(bills) → 20
%zu Format specifier for printing a sizeof result printf("%zu", sizeof(x));
Off-by-one error A loop that runs one time too many or too few i <= 5 instead of i < 5
Array parameter An array passed to a function; the function gets its start address int total(int bills[], int n)
Address The location of something in memory (more in episode 10) where bills starts
2D array An array of arrays: a table of rows and columns int sales[3][4];
Row / column First index = row, second index = column sales[1][2]: row 1, column 2
Nested loop A loop inside a loop, used to walk a table for r { for d { ... } }

Summary

  • An array is one name with numbered slots of one type: int bills[5] = {120, 45, 80, 200, 60};.
  • Indexes run from 0 to size − 1; loop with i < size.
  • Going out of bounds is undefined behavior: no error, just wrong answers or crashes.
  • Count the slots with sizeof(a) / sizeof(a[0]) (only where the array was declared).
  • Missing initial values become 0; no initialiser at all means garbage.
  • Arrays can't be assigned with =; copy them slot by slot.
  • Pass the size with an array; a function works on the real array and can change it.
  • A 2D array is a table: a[row][column], walked with nested loops.

Next episode: strings. Bhaiya wants the customer's name on every bill, and a name is just a row of letters: an array of characters, with one surprise of its own.