Nested loops in C++ - Time & Space Complexity
When we use loops inside other loops, the time it takes to run the code can grow quickly.
We want to understand how the total work changes as the input size gets bigger.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// some constant time operation
std::cout << i * j << std::endl;
}
}
This code prints the product of i and j for every pair of numbers from 0 to n-1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner loop runs a print operation.
- How many times: The inner loop runs n times for each of the n iterations of the outer loop, so n x n times total.
As n grows, the total operations grow much faster because of the two loops inside each other.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 |
| 100 | 10,000 |
| 1000 | 1,000,000 |
Pattern observation: When n gets 10 times bigger, the work gets 100 times bigger because of the nested loops.
Time Complexity: O(n²)
This means the work grows by the square of the input size, so doubling n makes the work about four times bigger.
[X] Wrong: "The time grows just a little bit because the loops are simple."
[OK] Correct: Because the inner loop runs completely for each outer loop step, the total work multiplies, not just adds.
Understanding nested loops helps you explain how your code handles bigger inputs and shows you can think about efficiency clearly.
"What if the inner loop ran only half as many times as the outer loop? How would the time complexity change?"
Practice
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
// code
}
}Solution
Step 1: Understand the code structure
The code shows oneforloop inside anotherforloop, which means nested loops.Step 2: Define nested loops
Nested loops mean one loop runs inside another loop's block of code.Final Answer:
A loop inside another loop -> Option BQuick Check:
Nested loop = loop inside loop [OK]
- Thinking loops run one after another, not inside
- Confusing nested loops with single loops
- Assuming nested loops run only once
Solution
Step 1: Identify C++ loop syntax
C++ usesfor(initialization; condition; increment)syntax for loops.Step 2: Check each option
for i in range(3): for j in range(2): /* code */uses Python syntax, invalid in C++.for(int i=0; i<3; i++) { for(int j=0; j<2; j++) { /* code */ } }uses correct C++ syntax with nestedforloops.while(i<3) { while(j<2) /* code */ }useswhileloops missing initializations and increments.loop(i=0; i<3; i++) { loop(j=0; j<2; j++) { /* code */ } }uses invalidloopkeyword.Final Answer:
for(int i=0; i<3; i++) { for(int j=0; j<2; j++) { /* code */ } } -> Option AQuick Check:
C++ nested loops use for(init; cond; inc) [OK]
- Using Python or other language syntax in C++
- Missing semicolons in for loop header
- Using wrong keywords like 'loop'
for(int i = 1; i <= 2; i++) {
for(int j = 1; j <= 3; j++) {
std::cout << i*j << " ";
}
std::cout << std::endl;
}Solution
Step 1: Trace outer loop values
Outer loop runs i=1 and i=2.Step 2: Calculate inner loop outputs
For i=1, j=1 to 3: outputs 1*1=1, 1*2=2, 1*3=3.
For i=2, j=1 to 3: outputs 2*1=2, 2*2=4, 2*3=6.Final Answer:
1 2 3 2 4 6 -> Option CQuick Check:
Multiply i and j in nested loops [OK]
- Ignoring the newline after inner loop
- Adding all numbers instead of printing products
- Confusing loop ranges
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; i++) {
std::cout << i+j << " ";
}
std::cout << std::endl;
}Solution
Step 1: Check inner loop increment
Inner loop header usesi++instead ofj++, causing infinite loop or wrong behavior.Step 2: Identify correct increment variable
Inner loop should incrementjto progress through its range.Final Answer:
Inner loop increments i instead of j -> Option AQuick Check:
Inner loop must increment its own variable [OK]
- Incrementing wrong variable in inner loop
- Assuming code runs without checking increments
- Confusing outer and inner loop variables
Solution
Step 1: Understand multiplication table logic
Each cell should print the product of row and column numbers (i*j).Step 2: Check each option's output logic
for(int i=1; i<=4; i++) { for(int j=1; j<=4; j++) { std::cout << i*j << " "; } std::cout << std::endl; } prints i*j correctly.
for(int i=0; i<4; i++) { for(int j=0; j<4; j++) { std::cout << i+j << " "; } std::cout << std::endl; } prints sum with zero-based indices.
for(int i=1; i<=4; i++) { for(int j=1; j<=4; j++) { std::cout << i+j << " "; } std::cout << std::endl; } prints sum with one-based indices.
for(int i=1; i<=4; i++) { for(int j=1; j<=4; j++) { std::cout << i-j << " "; } std::cout << std::endl; } prints difference.Final Answer:
for(int i=1; i<=4; i++) { for(int j=1; j<=4; j++) { std::cout << i*j << " "; } std::cout << std::endl; } -> Option DQuick Check:
Multiplication table = print i*j in nested loops [OK]
- Using addition or subtraction instead of multiplication
- Starting loops at 0 instead of 1 for table
- Not printing newline after each row
Ready to prove it?
Pass the test and this pattern moves unknown
