Bird
Raised Fist0
C++programming~5 mins

Multi-dimensional arrays in C++

Choose your learning style10 modes available
Introduction

Multi-dimensional arrays help you store data in tables or grids, like a chessboard or calendar.

When you want to store data in rows and columns, like a spreadsheet.
When you need to represent a game board, like tic-tac-toe or chess.
When working with images, where pixels are arranged in rows and columns.
When you want to store multiple sets of related data in a structured way.
When you need to perform mathematical operations on matrices.
Syntax
C++
class MultiDimensionalArray {
public:
    int rows;
    int cols;
    int data[3][4];  // fixed size 3 rows and 4 columns

    MultiDimensionalArray() {
        rows = 3;
        cols = 4;
        // Initialize all elements to zero
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < cols; ++col) {
                data[row][col] = 0;
            }
        }
    }

    void setValue(int row, int col, int value) {
        if (row >= 0 && row < rows && col >= 0 && col < cols) {
            data[row][col] = value;
        }
    }

    int getValue(int row, int col) {
        if (row >= 0 && row < rows && col >= 0 && col < cols) {
            return data[row][col];
        }
        return -1; // invalid index
    }

    void print() {
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < cols; ++col) {
                std::cout << data[row][col] << " ";
            }
            std::cout << std::endl;
        }
    }
};

The first index is the row number, the second is the column number.

Array sizes must be fixed at compile time in this example for simplicity.

Examples
Sets values at the first row, first column and last row, last column, then prints the whole array.
C++
MultiDimensionalArray array;
array.setValue(0, 0, 5);
array.setValue(2, 3, 10);
array.print();
Prints the array when all values are zero (empty).
C++
MultiDimensionalArray emptyArray;
emptyArray.print();
Sets and gets a single element in the middle of the array.
C++
MultiDimensionalArray singleElementArray;
singleElementArray.setValue(1, 2, 7);
std::cout << singleElementArray.getValue(1, 2) << std::endl;
Shows what happens if you try to access outside the array bounds.
C++
MultiDimensionalArray outOfBoundsArray;
outOfBoundsArray.setValue(5, 5, 100); // ignored
std::cout << outOfBoundsArray.getValue(5, 5) << std::endl; // prints -1
Sample Program

This program creates a 3x4 multi-dimensional array, prints it empty, sets some values, prints again, and shows how to get values safely.

C++
#include <iostream>

class MultiDimensionalArray {
public:
    int rows;
    int cols;
    int data[3][4];

    MultiDimensionalArray() {
        rows = 3;
        cols = 4;
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < cols; ++col) {
                data[row][col] = 0;
            }
        }
    }

    void setValue(int row, int col, int value) {
        if (row >= 0 && row < rows && col >= 0 && col < cols) {
            data[row][col] = value;
        }
    }

    int getValue(int row, int col) {
        if (row >= 0 && row < rows && col >= 0 && col < cols) {
            return data[row][col];
        }
        return -1;
    }

    void print() {
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < cols; ++col) {
                std::cout << data[row][col] << " ";
            }
            std::cout << std::endl;
        }
    }
};

int main() {
    MultiDimensionalArray gameBoard;

    std::cout << "Initial game board:" << std::endl;
    gameBoard.print();

    gameBoard.setValue(0, 0, 1); // top-left corner
    gameBoard.setValue(1, 2, 5); // middle
    gameBoard.setValue(2, 3, 9); // bottom-right corner

    std::cout << "\nGame board after setting some values:" << std::endl;
    gameBoard.print();

    int value = gameBoard.getValue(1, 2);
    std::cout << "\nValue at row 1, column 2: " << value << std::endl;

    int invalidValue = gameBoard.getValue(5, 5);
    std::cout << "Value at invalid position (5,5): " << invalidValue << std::endl;

    return 0;
}
OutputSuccess
Important Notes

Time complexity to access or set an element is O(1) because you use direct indexes.

Space complexity is fixed and depends on the array size (rows * columns).

Common mistake: Trying to access indexes outside the array size causes errors or unexpected results.

Use multi-dimensional arrays when you need fixed-size grids. For dynamic sizes, consider vectors or pointers.

Summary

Multi-dimensional arrays store data in rows and columns, like a table.

You access elements using two indexes: row and column.

They are useful for grids, game boards, and matrices.

Practice

(1/5)
1. What is a multi-dimensional array in C++?
easy
A. A variable that holds a single number
B. An array that stores only one value
C. A function that returns multiple values
D. An array with more than one index, like rows and columns

Solution

  1. Step 1: Understand array dimensions

    A multi-dimensional array uses multiple indexes to access elements, such as row and column in a table.
  2. Step 2: Compare options

    Only An array with more than one index, like rows and columns describes an array with more than one index, matching the concept of multi-dimensional arrays.
  3. Final Answer:

    An array with more than one index, like rows and columns -> Option D
  4. Quick Check:

    Multi-dimensional array = multiple indexes [OK]
Hint: Think of rows and columns in a table for multi-dimensional arrays [OK]
Common Mistakes:
  • Confusing arrays with single values
  • Thinking functions return multiple values
  • Mixing variables with arrays
2. Which of the following is the correct way to declare a 2D array of integers with 3 rows and 4 columns in C++?
easy
A. int arr[3][4];
B. int arr(3,4);
C. int arr[4][3];
D. int arr{3,4};

Solution

  1. Step 1: Recall C++ 2D array syntax

    The correct syntax uses square brackets with sizes: int arr[rows][columns];
  2. Step 2: Check each option

    int arr[3][4]; uses int arr[3][4]; which means 3 rows and 4 columns, correct syntax. Others are invalid or reversed.
  3. Final Answer:

    int arr[3][4]; -> Option A
  4. Quick Check:

    Use square brackets for dimensions [OK]
Hint: Use square brackets for rows and columns in declaration [OK]
Common Mistakes:
  • Using parentheses instead of brackets
  • Swapping row and column sizes
  • Using curly braces for declaration
3. What is the output of the following C++ code?
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
std::cout << arr[1][2];
medium
A. 6
B. 3
C. 4
D. 2

Solution

  1. Step 1: Understand array initialization

    The array has 2 rows and 3 columns: first row {1,2,3}, second row {4,5,6}.
  2. Step 2: Access element arr[1][2]

    Row index 1 is second row, column index 2 is third element: value is 6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    arr[1][2] = 6 [OK]
Hint: Remember indexes start at 0; arr[1][2] is second row, third column [OK]
Common Mistakes:
  • Confusing row and column indexes
  • Forgetting zero-based indexing
  • Reading wrong element from array
4. Identify the error in this C++ code snippet:
int matrix[2][2] = {{1, 2}, {3}};
std::cout << matrix[1][1];
medium
A. Missing value in second row initialization
B. Array size mismatch causes compile error
C. No error, code runs and prints 0
D. Incorrect use of std::cout syntax

Solution

  1. Step 1: Check array initialization

    The second row has only one value {3}, missing one element for 2 columns.
  2. Step 2: Understand C++ behavior for missing elements

    Missing elements are initialized to 0 automatically, so matrix[1][1] is 0.
  3. Step 3: Check output statement

    std::cout syntax is correct, so it prints 0 without error.
  4. Final Answer:

    No error, code runs and prints 0 -> Option C
  5. Quick Check:

    Missing elements default to 0 in arrays [OK]
Hint: Missing elements in array init become zero, no error [OK]
Common Mistakes:
  • Assuming missing elements cause errors
  • Thinking std::cout syntax is wrong
  • Expecting garbage values instead of zero
5. How can you sum all elements of a 3x3 integer array named grid in C++?
hard
A. Use std::accumulate directly on the 2D array
B. Use nested loops to add each element to a sum variable
C. Use a single loop from 0 to 8 to sum elements
D. Add only the first row elements

Solution

  1. Step 1: Understand 2D array traversal

    To access all elements in a 3x3 array, use two loops: one for rows, one for columns.
  2. Step 2: Sum elements with nested loops

    Inside inner loop, add each element grid[i][j] to a sum variable to get total sum.
  3. Final Answer:

    Use nested loops to add each element to a sum variable -> Option B
  4. Quick Check:

    Nested loops sum all elements [OK]
Hint: Use two loops: outer for rows, inner for columns [OK]
Common Mistakes:
  • Using single loop ignoring 2D structure
  • Summing only part of the array
  • Trying to use std::accumulate on 2D array directly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard