Recall & Review
beginner
What is a nested loop in C++?
A nested loop is a loop inside another loop. The inner loop runs completely every time the outer loop runs once.
Click to reveal answer
beginner
How many times will the inner loop run in this code?<br>
for(int i = 0; i < 3; i++) {<br> for(int j = 0; j < 2; j++) {<br> // inner loop body<br> }<br>}The inner loop runs 2 times for each of the 3 outer loop runs, so 3 × 2 = 6 times in total.
Click to reveal answer
beginner
Why do we use nested loops?
We use nested loops to work with multi-dimensional data, like tables or grids, or to repeat tasks inside other repeated tasks.
Click to reveal answer
intermediate
What happens if the inner loop depends on the outer loop variable?
The inner loop can change how many times it runs based on the outer loop variable, allowing more flexible patterns.
Click to reveal answer
beginner
Write a nested loop to print a 3x3 grid of stars (*) in C++.
for(int i = 0; i < 3; i++) {<br> for(int j = 0; j < 3; j++) {<br> std::cout << "* ";<br> }<br> std::cout << std::endl;<br>}Click to reveal answer
How many times does the inner loop run in this code?<br>
for(int i = 0; i < 4; i++) {<br> for(int j = 0; j < 3; j++) {<br> // code<br> }<br>}✗ Incorrect
The inner loop runs 3 times for each of the 4 outer loop runs, so 4 × 3 = 12 times.
What is the output of this nested loop?<br>
for(int i = 1; i <= 2; i++) {<br> for(int j = 1; j <= 2; j++) {<br> std::cout << i+j << " ";<br> }<br> std::cout << std::endl;<br>}✗ Incorrect
For i=1: j=1 (1+1=2), j=2 (1+2=3); for i=2: j=1 (2+1=3), j=2 (2+2=4).
Which statement is true about nested loops?
✗ Incorrect
The inner loop finishes all its iterations every time the outer loop runs once.
What is the time complexity of two nested loops each running n times?
✗ Incorrect
Two nested loops each running n times result in n × n = n² operations.
How can nested loops be useful in real life?
✗ Incorrect
Nested loops help handle multi-dimensional data like tables or grids.
Explain what nested loops are and give a simple example in C++.
Think about loops inside loops and how many times the inner loop runs.
You got /3 concepts.
Describe a real-world scenario where nested loops would be useful.
Imagine rows and columns or a chessboard.
You got /3 concepts.