2D Array
Program to work with 2D arrays (matrices)
IntermediateTopic: Array Programs
C++ 2D Array Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
int main() {
int rows, cols;
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> cols;
int matrix[rows][cols];
cout << "Enter matrix elements:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}
cout << "Matrix:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}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
Understanding 2D Array
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.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.