What is a 2D Array in C++?
A 2D array in C++ is like a table or grid — rows and columns of values. 📊
Imagine a 3×3 tic-tac-toe board. That’s a 2D array in action!
🧱 Syntax of a 2D Array
type arrayName[rows][columns];
For example:
int matrix[2][3]; // 2 rows, 3 columns
int table[2][2] = {{1, 2}, {3, 4}}; // Initialization
🔧 Example: Basic 2D Array
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
🧠 Accessing Elements
You can access any element using array[row][column]. For example, matrix[1][2] gives you 6.
🛠 Modify 2D Array Values
Just like 1D arrays, use the index to update values:
matrix[0][1] = 10;
💡 Summary
- A 2D array is a grid of values—rows and columns
- Use
array[row][col]to access or change elements - Great for tables, games, and matrix-style data
Now you can store data in a grid like a pro! 🧮