Algorithms

Arrays and matrices: why the index starts at zero

Cover of the article Arrays and matrices: why the index starts at zero
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does an array work?
  2. How do you create and go through an array?
  3. And what is a matrix?
  4. What are the most common mistakes with arrays?
  5. Where do arrays and matrices show up in everyday life?
  6. Now it’s your turn!

An array is a variable that stores several values, one next to the other, each one in a numbered position. A matrix is an array of arrays: the values are organized in rows and columns, like in a table.

In the article about variables, you learned how to store one value in one variable. But in the real world we almost never work with just one value, right? It’s the grades of a whole class, the products in a shopping cart, the contacts on your phone… That’s where arrays come in!!!

How does an array work?

So you never forget it, think of a chest of drawers. The whole piece of furniture has a single name, but each drawer has its own number. If I ask you to “grab what’s in drawer 2”, you know exactly where to look. The array is that chest of drawers: a single name for the variable and a number for each position. That number is called the index.

Now comes the detail that catches EVERY beginner haha: in most languages, the first drawer isn’t number 1. It’s number 0! IMPORTANT: the index starts at zero. Here’s what an array with four grades looks like:

Index0123
Value7.58.06.59.0
The “grades” array: four positions, numbered from 0 to 3.
Diagram of the grades array with four positions numbered from 0 to 3, each one holding a grade
The grades array: one name and four positions, numbered starting from zero.

How do you create and go through an array?

Let’s go to the code. As I always do here, I’ll show the same example in more than one language. Focus on the concept, not the language! The program stores four grades and calculates the average. First in PHP:

<?php

$grades = [7.5, 8.0, 6.5, 9.0];

echo $grades[0], PHP_EOL;       // 7.5 (the first position is 0)
echo count($grades), PHP_EOL;   // 4

$total = 0;
foreach ($grades as $grade) {
    $total += $grade;
}

echo $total / count($grades), PHP_EOL; // 7.75

Now the same program in Python:

grades = [7.5, 8.0, 6.5, 9.0]

print(grades[0])    # 7.5 (the first position is 0)
print(len(grades))  # 4

total = 0
for grade in grades:
    total += grade

print(total / len(grades))  # 7.75

And in C, where you need to state the size of the array right when you create it:

#include <stdio.h>

int main(void) {
    float grades[4] = {7.5, 8.0, 6.5, 9.0};
    float total = 0;

    for (int i = 0; i < 4; i++) {
        total += grades[i];
    }

    printf("%.2f\n", total / 4); // 7.75
    return 0;
}

Did you notice that the three versions do the same thing? They create the array, get a value by its index and use a loop to go through all the positions. Arrays and loops always go together!

A fun fact: in PHP, the array is more flexible than the classic array, like the one in C. The official manual explains that it’s actually an ordered map, which associates values to keys. That’s why PHP even lets you use text as an index. But that’s a topic for another article haha.

And what is a matrix?

If the array is a chest of drawers, the matrix is a spreadsheet: it has rows and columns. To find a value, you need two indexes: first the row, then the column. Here’s a tic-tac-toe board in PHP:

<?php

$board = [
    ['X', 'O', 'X'],
    ['O', 'X', 'O'],
    ['O', 'X', 'X'],
];

echo $board[1][2], PHP_EOL; // O (row 1, column 2)

Row 1 is the second row (remember the zero?), and column 2 is the third column. That’s why the result is O. Got it?

Diagram of the board matrix, three rows by three columns, with the position in row 1 and column 2 highlighted
In the matrix, the first number is the row and the second is the column: board[1][2] holds the O.
ArrayMatrix
ShapeA single line of valuesRows and columns
IndexesOne: the positionTwo: the row and the column
ExampleA student’s gradesBoard, spreadsheet, image
The difference between an array and a matrix.

What are the most common mistakes with arrays?

  • Forgetting that the index starts at zero. In an array with 4 positions, the last one has index 3, not 4.
  • Asking for a position that doesn’t exist. I tested it here: PHP 8 shows the warning Undefined array key 4 and keeps going, and Python stops the program with IndexError: list index out of range. C is the most dangerous: compiled with plain gcc, it gave no warning, read whatever was in that piece of memory and kept running. GCC only warned me when I compiled with -Wall -O2.
  • Swapping the order in the matrix. It’s always row first, column second.

Where do arrays and matrices show up in everyday life?

Everywhere!!! A list of products, the result of a database query, the pixels of an image, the squares of a board… Arrays and matrices are also the basis of almost every data structure, like the stack, and of classic exercises like the Hourglass Sum.

Now it’s your turn!

Create an array with the temperatures of the seven days of the week and find the highest one by going through the array with a loop. Choose whichever language you want.

Try it on your own, without asking anyone for the ready-made answer, not even AI! Don’t copy and paste: type, run, make mistakes and fix them. That’s how the concept leaves the screen and goes into your head. You have the same capacity as any programmer; all that’s missing is practice!

In the next article, we’ll talk about functions, which are the way to give a name to a piece of code so you can use it as many times as you want. See you there!

Stay confident!!!

Sources:

  • PHP, official manual. Arrays, with the PHP array as an ordered map that associates values to keys, and int and string keys in the same array.
  • PHP, official manual. foreach, with foreach as an easy way to iterate over arrays.
  • PHP, official manual. Backward Incompatible Changes (PHP 8.0), with reading an undefined array key among the notices converted into warnings.
  • Python, official documentation. Built-in Exceptions, with IndexError, raised when a sequence subscript is out of range.
  • Cornell University, Cornell Virtual Workshop. Introduction to Python Programming: Lists, with list elements accessed by their position, starting at 0.
  • GNU, The GNU C Language Manual. Accessing Array Elements, with 0 as the lowest valid index, the highest one less than the number of elements, and C not checking whether the index is in bounds.
  • Carnegie Mellon University, SEI CERT C Coding Standard. ARR30-C. Do not form or use out-of-bounds pointers or array subscripts, with the out-of-range subscript as undefined behavior.
  • Princeton University, COS 126 (Robert Sedgewick and Kevin Wayne). 1.4 Arrays (lecture slides), with a[i][j] as the element in row i and column j, and row and column indexes starting at 0.
  • Edsger W. Dijkstra (EWD831), University of Texas archive. Why numbering should start at zero, with the subscript of an element equal to the number of elements that come before it.
  • The examples were run on PHP 8.3, Python 3.13 and GCC 13.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).