Opening the reading…
Opening the reading…
DSA FUNDAMENTALS › CONTROL FLOW
For n = 4, the target has four rows and four numbers in every row. The first row repeats 1, the second repeats 2, and so on. The outer loop variable i identifies the current row, while the inner loop variable j visits the four positions within that row.
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4When i = 1, you are building the first row, so every cell in that row must print 1. When i = 2, every cell must print 2. The value of j tells you which position you are filling, but it does not decide the number shown in that position.
Which variable must you print to produce the target pattern for n = 4?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The outer loop gives i the values 1, 2, 3, and 4. For each value of i, the inner loop gives j the values 1, 2, 3, and 4. Since i is printed inside the inner loop, the same row number is printed once for every value of j.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
cout << i << ' ';
}
cout << '\n';
}Trace the second row. The outer loop sets i to 2. The inner loop then runs four times: when j is 1, print 2; when j is 2, print 2 again; when j is 3, print 2 again; and when j is 4, print 2 again. The row is therefore 2 2 2 2. After the inner loop finishes, the newline moves output to the next row.
The nested-loop shape does not make i and j interchangeable. If you print j, then each row prints 1 2 3 4, because j changes on every pass of the inner loop. The outer loop still creates four rows, but every row has the same changing sequence.
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4The target needs the number to stay fixed while the inner loop moves across a row. Replace j in the print statement with i. Then the first inner-loop pass changes from printing 1 when i = 1 to printing the current row number, and the second inner-loop pass does the same. For i = 2, both passes print 2, and the remaining two passes also print 2.
Replace the wrong variable so this inner statement produces the target pattern.
cout << j << ' ';Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The number and its separator belong inside the inner loop because they must be printed four times. The newline belongs immediately after that loop because one row is complete only after all four positions have been printed. For i = 3, the four inner-loop passes print 3, 3, 3, and 3 as j moves from 1 to 4. Then one newline completes the row.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
cout << i << ' ';
}
cout << '\n';
}