for i = 0 to 2
for j = 0 to 3
arr[i][j] = i + j
#include <iostream>
using namespace std;
int main(){
int arr[3][4] =
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
arr[i][j] = i + j;
}
}
}
The above code creates a 3x4 array and assigns the sum of i and j to each element.
0 | 1 | 2 | 3 |
1 | 2 | 3 | 4 |
2 | 3 | 4 | 5 |
To display a 2D array, you need to use two nested loops to iterate through each element.
You can imagine i is the row and j is the column.
So for each row (i), display value of each "box" (j).
#include <iostream>
using namespace std;
int main(){
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for(int i = 0; i < 3; i++){ // Outer loop for row
for(int j = 0; j < 3; j++){ // Inner loop for column (each box)
cout << arr[i][j] << " ";
}
cout << endl; // After finish each row, start a new line
}
}
Final values should be:
1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 |
You need to think about how to fill the array with the correct values by using +-*/ operations to i and j in the loop.
#include <iostream>
using namespace std;
int main(){
int arr[4][4];
int i, j;
for(i = 0; i < 4; i++){
for(j = 0; j < 4; j++){
arr[i][j] = _________________________________ ;
}
}
// Display the array with nested loop
}
Fill a 3x3 array with random numbers between 1 to 9 and output the array.
All numbers should be unique.
Sample output:
4 2 7
5 1 9
3 6 8