LearnForFree
C++ For Beginners
Lesson

C-Style Arrays & Multidimensional Arrays

An array is a fixed-size collection of elements of the exact same data type stored in contiguous (back-to-back) memory locations. Instead of creating 50 separate int variables for student grades, you can store all 50 inside a single array. • Zero-Based Indexing: Array indices start at 0, not 1. In an array of size 5, the valid indices are 0, 1, 2, 3, 4. Accessing scores[5] goes out of bounds and causes undefined behavior or a crash. • Fixed Size: Once declared, a C-style array cannot grow or shrink while the program runs. • Calculating Array Length: You can find the number of elements using sizeof(scores) / sizeof(scores[0]) (or std::size(scores) in C++17 and newer). 2. Multidimensional Arrays (2D Arrays) A 2D array is an array of arrays, commonly used to represent grids, tables, spreadsheets, or game boards (like Tic-Tac-Toe or Chess). It requires two indices: [row][column].
#include <iostream> int main() { // 1. One-Dimensional Array int numbers[4] = {10, 20, 30, 40}; numbers[1] = 25; // Modifies the second element (index 1) std::cout << "1D Array elements: "; for (int i = 0; i < 4; i++) { std::cout << numbers[i] << " "; } std::cout << "\n\n"; // 2. Two-Dimensional Array (2 rows, 3 columns) int matrix[2][3] = { {1, 2, 3}, // Row 0 {4, 5, 6} // Row 1 }; std::cout << "Element at Row 1, Col 2: " << matrix[1][2] << "\n"; // Outputs 6 // Nested loops to print the entire 2D grid std::cout << "Full 2D Matrix:\n"; for (int row = 0; row < 2; row++) { for (int col = 0; col < 3; col++) { std::cout << matrix[row][col] << " "; } std::cout << "\n"; } return 0; }

Watch companion video on YouTube

Sign in to save your progress