🇯🇵 日本語 | 🇺🇸 English
Advertisement

Quiz (Loops)

Test your understanding of for, while, break, and nested loops.

Question 1 — Iteration count of a for loop

int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum += i;
}
printf("sum = %d\n", sum);

What does this print?

sum = 5
sum = 15
sum = 10
sum = 14
Explanation: The loop runs 5 times with i=1,2,3,4,5.
1+2+3+4+5 = 15.

Question 2 — while loop termination

int x = 10;
while (x > 0) {
    x -= 3;
}
printf("x = %d\n", x);

What does this print?

x = 0
x = 1
x = -2
x = 3
Explanation: x changes: 10 → 7 → 4 → 1 → -2.
When x=-2, x > 0 is false and the loop ends. Since x -= 3 subtracts 3 each time, the loop can overshoot 0.

Question 3 — break behavior

for (int i = 0; i < 10; i++) {
    if (i == 3) break;
    printf("%d ", i);
}

What does this print?

0 1 2 3
0 1 2
0 1 2 3 4 5 6 7 8 9
3
Explanation: When i==3, break exits the loop immediately. The break happens before printf, so 3 is never printed.
Output is just 0 1 2 (i=0,1,2).

Question 4 — Nested loop iterations

int count = 0;
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        count++;
    }
}
printf("count = %d\n", count);

What does this print?

count = 7
count = 12
count = 3
count = 4
Explanation: Outer loop 3 times × inner loop 4 times = 12 iterations.
The total iteration count of a nested loop is outer × inner.

Result

Please answer the questions
Home