0
0
C++programming~20 mins

Nested loops in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Loops Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested loops with break
What is the output of this C++ code snippet?
C++
#include <iostream>
int main() {
    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j) {
            if (j == 2) break;
            std::cout << i << j << " ";
        }
    }
    return 0;
}
A12 22 32
B11 12 13 21 22 23 31 32 33
C11 21 31
D11 12 21 22 31 32
Attempts:
2 left
💡 Hint
Look at where the break statement stops the inner loop.
Predict Output
intermediate
2:00remaining
Counting iterations in nested loops
How many times will the inner statement execute in this code?
C++
#include <iostream>
int main() {
    int count = 0;
    for (int i = 0; i < 4; ++i) {
        for (int j = i; j < 4; ++j) {
            ++count;
        }
    }
    std::cout << count;
    return 0;
}
A10
B16
C6
D12
Attempts:
2 left
💡 Hint
Count how many times j runs for each i.
🔧 Debug
advanced
2:00remaining
Identify the error in nested loops
What error will this code produce when compiled?
C++
#include <iostream>
int main() {
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            std::cout << i << j << std::endl;
    std::cout << "Done" << std::endl;
    return 0;
}
ACompilation error: undeclared variable
BCompilation error: missing braces
CRuntime error: segmentation fault
DRuns and prints pairs then 'Done'
Attempts:
2 left
💡 Hint
Check how indentation affects loops in C++.
Predict Output
advanced
2:00remaining
Output of nested loops with continue
What is the output of this code?
C++
#include <iostream>
int main() {
    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j) {
            if (i == j) continue;
            std::cout << i << j << " ";
        }
    }
    return 0;
}
A11 22 33
B12 13 21 23 31 32
C12 13 23 31 32
D21 23 31 32
Attempts:
2 left
💡 Hint
The continue skips printing when i equals j.
🧠 Conceptual
expert
3:00remaining
Number of iterations in nested loops with variable limits
Consider this nested loop code. How many times does the innermost statement execute?
C++
#include <iostream>
int main() {
    int count = 0;
    for (int i = 1; i <= 5; ++i) {
        for (int j = 1; j <= i; ++j) {
            for (int k = 1; k <= j; ++k) {
                ++count;
            }
        }
    }
    std::cout << count;
    return 0;
}
A35
B55
C50
D45
Attempts:
2 left
💡 Hint
Sum the counts: for each i, sum j=1 to i, then sum k=1 to j.