📦 Section 2 · Arrays & Pointers 🟢 Beginner MODULE 06

Arrays — 1D and 2D

⏱️ 25 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Section 220%
🎯 What you'll learn: How to declare and initialize fixed-size C++ arrays, how 0-based indexing works, how to loop over an array safely, why arrays don't know their own length, and how to build and traverse a 2D array like a grid or a small board.

What Is an Array?

An array is a fixed-size, ordered block of memory that holds multiple values of the same type, laid out one right after another. Instead of creating five separate variables to hold five test scores, you create one array that holds all five.

In C++, a plain array has a size that is fixed the moment it's declared — you cannot grow or shrink it later. Every element sits at a specific position called an index, and indexing always starts at 0, not 1.

💡
Think of an array as a row of numbered lockers
Locker 0 is the first locker, not locker 1. If you have 5 lockers, the last one is locker 4 — not locker 5. This 0-based counting trips up almost every beginner at least once, so get comfortable with it now.
🔢
0-Based Indexing
The first element is at index 0, the last is at index (size - 1).
📏
Fixed Size
Once declared, a plain C++ array cannot change size at runtime.
🧱
Same Type Only
Every element in an array must share the same data type.
📍
Contiguous Memory
Elements are stored back-to-back in memory, which makes access fast.

Declaring and Initializing Arrays

You declare a fixed-size array by writing the element type, a name, and the number of elements in square brackets. You can initialize it immediately with a comma-separated list of values inside curly braces.

arrays_basic.cpp — Declaring & Printing an Array
C++
// arrays_basic.cpp
#include <iostream>
using namespace std;

int main() {
    int scores[5] = {90, 85, 78, 92, 88};

    for (int i = 0; i < 5; i++) {
        cout << "Score " << i << ": " << scores[i] << endl;
    }

    return 0;
}

The array scores holds exactly 5 int values, indexed 0 through 4. You can also declare an array without listing every value up front — uninitialized elements of a local array will contain garbage values until you assign them, so always initialize your arrays.

⚠️
C++ does not check array bounds for you
Writing to scores[10] on a 5-element array compiles fine and may not crash immediately — it silently reads or writes memory that doesn't belong to the array. This is called undefined behavior, and it's one of the reasons C++ demands careful, disciplined code.

Iterating Arrays with Loops

A plain for loop is the most common way to walk through every element of an array — reading each value, summing them, or searching for something specific.

arrays_sum_max.cpp — Sum & Maximum
C++
// arrays_sum_max.cpp
#include <iostream>
using namespace std;

int main() {
    int nums[6] = {12, 45, 7, 89, 23, 56};
    int size = sizeof(nums) / sizeof(nums[0]); // 6

    int sum = 0;
    int maxVal = nums[0];

    for (int i = 0; i < size; i++) {
        sum += nums[i];
        if (nums[i] > maxVal) {
            maxVal = nums[i];
        }
    }

    cout << "Sum: " << sum << endl;
    cout << "Max: " << maxVal << endl;

    return 0;
}

Notice how size is calculated once at the top and reused in the loop condition — that's a much safer habit than hardcoding 6 in multiple places, especially once the array grows or shrinks during development.

Array Size Gotchas

Unlike Python lists or JavaScript arrays, a plain C++ array does not know its own length at runtime. There is no .length or .size() built into it. The sizeof(arr) / sizeof(arr[0]) trick you just saw works — but only in the exact same scope where the array was declared.

⚠️
The sizeof trick breaks once an array is passed to a function
When an array is passed into a function, it "decays" into a plain pointer to its first element — and a pointer's sizeof is just the size of an address (commonly 8 bytes), not the whole array. Because of this, most C++ code tracks array size in a separate variable and passes it alongside the array. You'll see exactly why this decay happens in Lesson 8 on pointers.

For now, the practical rule is simple: always know your array's size independently — either compute it with sizeof right where the array is declared, or store it in a constant or variable you pass around together with the array.

2D Arrays — A Grid of Values

A 2D array is an array of arrays — think of it as a table with rows and columns. You declare it with two sets of square brackets: type name[rows][cols]. To visit every cell, you nest two for loops — an outer loop for rows, an inner loop for columns.

board.cpp — A 3x3 Grid
C++
// board.cpp
#include <iostream>
using namespace std;

int main() {
    char board[3][3] = {
        {'X', 'O', 'X'},
        {'O', 'X', 'O'},
        {'X', 'X', 'O'}
    };

    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            cout << board[row][col] << " ";
        }
        cout << endl;
    }

    return 0;
}

Here board[row][col] reaches the exact cell at that row and column. This same pattern — outer loop for rows, inner loop for columns — is how you'd process a small spreadsheet, a game board, a black-and-white image, or a simple matrix.

Reading the declaration left to right
char board[3][3] means: 3 rows, each row is itself an array of 3 chars. So board[1] refers to the whole second row, and board[1][2] refers to the third element of that row.

Lesson Summary

Let's recap everything you learned in this lesson:

Arrays hold multiple values of the same type in one fixed-size block of memory.
Indexing is 0-based — the last valid index is size - 1.
C++ does not check array bounds — going out of range is undefined behavior.
Use sizeof(arr) / sizeof(arr[0]) to find an array's length — but only in the scope where it was declared.
2D arrays are declared as type name[rows][cols] and traversed with nested loops.
🧩 Knowledge Check — Lesson 6
Answer all 5 questions to test your understanding. Instant feedback on every answer.
1. What is the index of the first element in a C++ array?
2. What does int arr[5]; declare?
3. Which expression correctly computes the number of elements in a stack-declared array arr in the scope it was defined?
4. Given int grid[3][4];, how many total elements does it hold?
5. What happens if you access arr[10] on an array declared with only 5 elements?
💪
Coding Challenge — Lesson 6
Apply what you learned · Beginner Level

Now it's your turn to write real code. Complete the challenge below in your own C++ environment.

Challenge: Find the Maximum Value 🏔️

Write a C++ program called find_max.cpp that declares an int array with at least 6 values of your choice, then finds and prints the largest value in the array using a loop.

Rules: Do not hardcode the answer — your loop must actually compare every element. Use sizeof(arr) / sizeof(arr[0]) to compute the array's length instead of a hardcoded number. Print a message like "Max value: 92".
💡 Show hints if you're stuck
  • Start by assuming arr[0] is the biggest — store it in a variable called maxVal
  • Loop from index 1 to the end, and whenever you find something bigger than maxVal, update it
  • Compute size once with int size = sizeof(arr) / sizeof(arr[0]);
  • Print the result with cout << "Max value: " << maxVal << endl;
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 6 Complete!

You now understand fixed-size arrays and 2D grids — the foundation for everything that comes next in this section, including strings and pointers.

Module 06 of 26 Section 2 — Arrays, Strings & Pointers