Interview Questions
C Loops · Study material
C Loops Interview Questions and Answers
1. What is the difference between while and do-while?
A while loop tests its condition before each pass and may run zero times; do-while tests after, so its body runs at least once.
2. In what order are the parts of a for loop executed?
Initialisation once; then condition, body, update – repeated until the condition is false.
3. What does continue do in a for loop?
It skips the rest of the body and jumps to the update expression, then the condition is tested again.
4. How many loops does break exit?
Only the innermost enclosing loop (or switch).
5. How do you write an infinite loop?
for (;;) or while (1). They are used for servers, event loops and embedded main loops, and are left with break or return.
6. Why is for (unsigned i = n; i >= 0; i--) a bug?
An unsigned value is never negative, so the condition is always true; after 0, i wraps to UINT_MAX.
7. Why should a loop counter not be a float?
Values like 0.1 are not exact in binary, so the counter drifts and may skip the end value; the loop can run one time too many or forever.
8. What is the time complexity of two nested loops of n?
O(n²) – the inner body runs n × n times. If the inner loop starts at the outer index, it runs n(n + 1)/2 times, still O(n²).
9. Can the loop variable of a for loop be used after the loop?
Not if it is declared in the header (C99 and later): its scope ends with the loop. Declare it before the loop if you need its final value.
10. What is a sentinel value?
A special input value (such as −1) that marks the end of the data and stops the loop.
11. Why are macros written as do { … } while (0)?
So that a multi-statement macro acts as a single statement and needs a semicolon, keeping it safe inside if/else without braces.
12. Inside a switch in a loop, what do break and continue do?
break leaves the switch only; continue goes to the next pass of the loop, because switch does not handle continue.