Which loop always executes its body at least once?
do-while checks its condition after the body, so the body runs once before the first test. for and while test first and may run zero times.
C Loops · Exercise 1 of 4
Twelve multiple-choice questions on for, while and do-while, break and continue, loop scope, unsigned and floating-point counters, and nested-loop complexity. Pick an option to check your answer instantly.
Which loop always executes its body at least once?
do-while checks its condition after the body, so the body runs once before the first test. for and while test first and may run zero times.
What does for (;;) { … } do?
All three parts of a for header are optional, and an empty condition is treated as true. for (;;) is the classic infinite loop, left with break or return.
In a for loop, where does continue transfer control?
continue ends the current pass. In a for loop the update (i++) still runs, then the condition. In a while loop it jumps straight to the condition – which is why a continue before the increment of a while loop can cause an infinite loop.
break is executed inside the inner loop of two nested loops. What happens?
break leaves the innermost enclosing loop or switch only. To leave both, use a flag, a return from a function, or a goto to a label after the loops.
How many times does the body of for (int i = 0; i < 10; i += 3) run?
i takes the values 0, 3, 6 and 9; the next value, 12, fails the test. That is 4 passes – ⌈10 / 3⌉.
After for (int i = 0; i < 5; i++) { … }, can you use i on the next line?
A variable declared in the for initialisation exists only for the loop. Declare it before the loop if you need its final value.
How many times does for (unsigned i = 10; i >= 0; i--) run?
After 0, decrementing an unsigned value wraps to UINT_MAX, so i >= 0 is always true. Compilers warn "comparison is always true". Count down with for (unsigned i = 11; i-- > 0; ) or use a signed counter.
What is the risk in for (float x = 0.0f; x != 1.0f; x += 0.1f)?
0.1 has no exact binary representation, so the sum drifts and can step over 1.0. Count with an integer and compute the value: for (int k = 0; k <= 10; k++) { float x = k / 10.0f; … }.
Both loops run from 0 to n − 1. How many times does the inner body execute?
The inner loop runs n times for each of the n outer passes: n × n = n² – O(n²) time. Doubling n makes such code about four times slower.
What is the difference between while (1) and for (;;)?
Both are infinite loops, and compilers generate identical code. for (;;) is sometimes preferred because some older compilers warned about the constant condition in while (1).
Timed online tests with instant scores and explanations.