0
0
C++programming~20 mins

Why loops are needed in C++ - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Loop Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple for loop
What is the output of this C++ code snippet?
C++
#include <iostream>
int main() {
    for (int i = 1; i <= 3; i++) {
        std::cout << i << " ";
    }
    return 0;
}
A1 2 3
B0 1 2 3
C1 2 3 4
D3 2 1
Attempts:
2 left
💡 Hint
The loop starts at 1 and runs while i is less than or equal to 3.
🧠 Conceptual
intermediate
1:30remaining
Why use loops instead of repeated code?
Why are loops useful in programming compared to writing the same code multiple times?
ALoops increase the size of the program by duplicating code.
BLoops reduce code repetition and make programs shorter and easier to maintain.
CLoops are only used to confuse beginners and have no real benefit.
DLoops make programs run slower by repeating code unnecessarily.
Attempts:
2 left
💡 Hint
Think about how many times you want to do the same task.
Predict Output
advanced
2:30remaining
Output of nested loops
What is the output of this nested loop code?
C++
#include <iostream>
int main() {
    for (int i = 1; i <= 2; i++) {
        for (int j = 1; j <= 2; j++) {
            std::cout << i << j << " ";
        }
    }
    return 0;
}
A11 21 12 22
B21 22 11 12
C12 11 22 21
D11 12 21 22
Attempts:
2 left
💡 Hint
The outer loop controls the first digit, the inner loop controls the second digit.
🔧 Debug
advanced
2:00remaining
Identify the error in this loop
What error will this code produce when compiled or run?
C++
#include <iostream>
int main() {
    for (int i = 0; i < 5; i++)
        std::cout << i << std::endl;
    std::cout << j;
    return 0;
}
ACompilation error: 'j' was not declared in this scope
BRuntime error: division by zero
CNo error, prints numbers 0 to 4 and then 0
DCompilation error: missing semicolon after for loop
Attempts:
2 left
💡 Hint
Check if all variables used are declared.
🚀 Application
expert
2:30remaining
Count how many times a loop runs
How many times will the loop body execute in this code?
C++
#include <iostream>
int main() {
    int count = 0;
    for (int i = 10; i > 0; i -= 3) {
        count++;
    }
    std::cout << count;
    return 0;
}
A5
B3
C4
D6
Attempts:
2 left
💡 Hint
Start from 10 and subtract 3 each time until i is no longer greater than 0.