Welcome to Chapter 2! 📦
The array is the most basic and most widely used data structure in programming. Almost every other data structure in this masterclass is built on top of arrays or compared against them, so understanding them well makes everything that follows easier.
By the end of this lesson, you will understand:
- What an array is
- Why array positions start at 0
- How an array is stored in memory, and why that makes it fast
- How to loop through an array
- When to use an array, and when not to
What Is an Array?
An array is a collection of items stored in order, one after another, where each item has a numbered position called an index.
Think of a row of numbered lockers at a railway station:
- Every locker sits right next to the previous one.
- Every locker has a number painted on it.
- If you know the number, you walk straight to that locker. You don't open the others.
Here is an array of five students' marks:
index: 0 1 2 3 4
+-----+-----+-----+-----+-----+
marks: | 72 | 85 | 90 | 64 | 88 |
+-----+-----+-----+-----+-----+
The array is called marks, it holds 5 items, and the indexes run from 0 to 4.
Why Does the Index Start at 0?
This surprises almost everyone at first. The index isn't "which number item is this?", it is "how many steps from the start?"
- The first item is 0 steps from the start, so it is index
0. - The second item is 1 step away, so it is index
1. - The last item of a 5-item array is 4 steps away, so it is index
4.
So for an array with n items, the indexes always run from 0 to n - 1.
Creating and Using an Array
You read an item with marks[index] and change it the same way:
public class Main {
public static void main(String[] args) {
int[] marks = {72, 85, 90, 64, 88};
System.out.println(marks[0]); // 72 (first item)
System.out.println(marks[4]); // 88 (last item)
marks[2] = 95; // change the third item
System.out.println(marks[2]); // 95
System.out.println(marks.length); // 5
}
}How an Array Works in Memory
This is the logic that makes arrays special.
Your computer's memory is like a very long street of houses, and every house has an address. When you create an array, the computer reserves a block of houses right next to each other and stores the items in order.
Suppose the array starts at address 1000, and each number takes up 4 bytes of memory (a typical size for an integer):
index: 0 1 2 3 4
+------+------+------+------+------+
value: | 72 | 85 | 90 | 64 | 88 |
+------+------+------+------+------+
address: 1000 1004 1008 1012 1016
Now, how does the computer find marks[3]? It doesn't search at all. It just calculates:
address = start + (index × size)address = 1000 + (3 × 4) = 1012
One quick calculation, and it jumps straight there. That is why reading any item of an array takes the same tiny amount of time, whether it is item 3 or item 3,000,000.
Reading an item by its index is
O(1). The position is calculated, never searched for. This is the single biggest strength of arrays.
Python lists and JavaScript arrays are a little more flexible under the hood than this picture, but the idea is the same: items are kept in order, and you reach any of them instantly by its index.
Looping Through an Array
To do something with every item, like adding up all the marks, you use a loop that visits index 0, then 1, then 2, and so on until the end:
public class Main {
public static void main(String[] args) {
int[] marks = {72, 85, 90, 64, 88};
int total = 0;
for (int i = 0; i < marks.length; i++) { // i = 0, 1, 2, 3, 4
total += marks[i];
}
System.out.println("Total: " + total); // Total: 399
System.out.println("Average: " + (double) total / marks.length); // Average: 79.8
}
}The loop runs once per item, so looping through an array is O(n), exactly as we saw with Big-O in Chapter 1.
When you don't need the index, most languages have a shorter form: for (int mark : marks) in Java, for mark in marks in Python, and for (const mark of marks) in JavaScript. C doesn't have one, so you always use the index.
What If You Go Past the End?
A very common beginner mistake is asking for an index that doesn't exist, like marks[10] on a 5-item array. Each language reacts differently:
| Language | What happens with marks[10] |
|---|---|
| Java | Stops with an ArrayIndexOutOfBoundsException error |
| Python | Stops with an IndexError |
| JavaScript | Quietly gives you undefined |
| C | Undefined behaviour: it may read random memory, crash, or even seem to work |
C is the most dangerous here. It doesn't check for you, so a wrong index can silently read or overwrite memory that belongs to something else. Always make sure your loop stops at n - 1.
Why Use an Array?
Arrays are great when:
- You need to reach items by position quickly
- You know roughly how many items you will have
- You mostly read and loop through data, like marks, prices or daily temperatures
Arrays are not great when:
- You often insert or remove items in the middle. Every item after that point has to shift over by one to make or close the gap.
| Operation | Big-O | Why |
|---|---|---|
| Read or change an item by index | O(1) | The address is calculated directly |
| Find a value in an unsorted array | O(n) | You may need to check every item |
| Add an item at the end | O(1) usually | Just place it in the next free slot |
| Insert or delete in the middle | O(n) | The items after it must all shift |
In the next lesson, we will look at the different types of arrays: grids, arrays that grow, and more.
Remember This
If you remember only one thing from this lesson, remember: An array stores items side by side in memory, so the computer can calculate exactly where any item is. Reading by index is instant, but inserting in the middle is slow.