get elements of 2d array c++
To get elements of a 2D array in C++, you can use nested loops to iterate over the rows and columns of the array. Here are the steps to do this:
- Declare and initialize a 2D array:
int arr[ROW][COL];
Replace ROW
and COL
with the desired number of rows and columns for your array.
- Use nested loops to iterate over the rows and columns of the array:
for(int i = 0; i < ROW; i++) {
for(int j = 0; j < COL; j++) {
// Access and use the element at arr[i][j]
}
}
The outer loop iterates over the rows, and the inner loop iterates over the columns.
- Access and use the element at
arr[i][j]
: Inside the nested loops, you can access and use the element at the current row and column using the indicesi
andj
. For example, you can print the element:
cout << arr[i][j] << " ";
Replace cout
with the appropriate output stream for your program.
Here's the complete code snippet:
#include <iostream>
using namespace std;
int main() {
const int ROW = 3;
const int COL = 4;
int arr[ROW][COL] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
for(int i = 0; i < ROW; i++) {
for(int j = 0; j < COL; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
This code snippet declares a 2D array arr
with 3 rows and 4 columns, assigns some values to it, and then uses nested loops to print all the elements of the array.