c++ fill two dimensional array
To fill a two-dimensional array in C++, you can use nested loops to iterate through each element of the array and assign a value to it. Here is an example of how to do that:
#include <iostream>
int main() {
const int rows = 3;
const int columns = 4;
int arr[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
arr[i][j] = i * columns + j;
}
}
return 0;
}
In this example, we have defined a two-dimensional array arr
with rows
rows and columns
columns. We use nested for
loops to iterate over each element of the array. The outer loop iterates over the rows, and the inner loop iterates over the columns.
Inside the inner loop, we assign a value to each element of the array using the formula i * columns + j
. This formula calculates a unique value for each element based on its row and column indices. You can modify this formula to assign different values based on your requirements.
After running the code, the two-dimensional array will be filled with values. You can then use the array for further operations or display the values using another set of nested loops.
I hope this helps! Let me know if you have any further questions.