0
0
C++programming~5 mins

Nested loops in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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>}
A12
B7
C4
D3
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>}
A1 1 \n 2 2
B1 2 \n 2 3
C2 3 \n 3 4
D3 4 \n 4 5
Which statement is true about nested loops?
AInner loop runs completely for each outer loop iteration.
BOuter loop runs completely for each inner loop iteration.
CBoth loops run only once.
DNested loops cannot be used with for loops.
What is the time complexity of two nested loops each running n times?
AO(n)
BO(n^2)
CO(1)
DO(log n)
How can nested loops be useful in real life?
ATo avoid repeating tasks.
BTo print a single number once.
CTo run only one loop.
DTo process rows and columns in a table.
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.