2D Array in C++
Work with 2D arrays (matrices) in C++.
IntermediateArray ProgramsExample 4 of 4
2d-array.cpp
1#include <iostream>2using namespace std;34int main() {5 int rows, cols;67 cout << "Enter number of rows: ";8 cin >> rows;9 cout << "Enter number of columns: ";10 cin >> cols;1112 int matrix[rows][cols];1314 cout << "Enter matrix elements:" << endl;15 for (int i = 0; i < rows; i++) {16 for (int j = 0; j < cols; j++) {17 cin >> matrix[i][j];18 }19 }2021 cout << "Matrix:" << endl;22 for (int i = 0; i < rows; i++) {23 for (int j = 0; j < cols; j++) {24 cout << matrix[i][j] << " ";25 }26 cout << endl;27 }2829 return 0;30}
Output
Enter number of rows: 3 Enter number of columns: 3 Enter matrix elements: 1 2 3 4 5 6 7 8 9 Matrix: 1 2 3 4 5 6 7 8 9
What's going on
A 2D array (matrix) is an array of arrays. We use nested loops to read and display elements. The first index represents the row, and the second index represents the column. This structure is useful for representing tabular data.