All topics
Loops
for, while, do-while, range-for, break and continue, off-by-one errors and unsigned counters.
Sort:
3 questions
JuniorTheoryCommonWhat does the program print?
JuniorTheoryCommon
What does the program print?
135
Open full question →Common mistakes
- ✗Expecting
1: that is whatbreakdoes;continueends only the current iteration, and the loop goes on with the next value ofi. - ✗Expecting the loop never to stop: in a
forloop,continuestill runs the step++i, soikeeps growing and the loop ends after5.
Follow-up questions
- →What would the program print if
continuewere replaced withbreak? - →Why can
continuemake awhileloop endless when its counter is incremented at the end of the body?
JuniorTheoryCommonWhat does the program print?
JuniorTheoryCommon
What does the program print?
6 4
Open full question →Common mistakes
- ✗Expecting
5 4:<=letsireach the bound, so the first loop runs for0,1, …5, six values in all, not five. - ✗Expecting
6 5: the second loop starts at1, soitakes only the values1to4, and the body runs four times.
Follow-up questions
- →How would you write a
forloop whose body runs exactlyntimes? - →What goes wrong if a loop like the first one reads the elements of a 5-element array?
JuniorTheoryCommonWhat happens when you build and run this program?
JuniorTheoryCommon
What happens when you build and run this program?
It prints 2, 1, 0, then the largest unsigned value, and never stops
Common mistakes
- ✗Expecting the loop to stop at -1: an
unsignedvalue is never negative, so--iat0gives the largestunsignedvalue andi >= 0stays true. - ✗Expecting undefined behavior: only signed overflow is undefined;
unsignedarithmetic wraps around by definition, so the loop keeps printing.
Follow-up questions
- →How would you rewrite this countdown so it prints
2,1,0and stops, keepingiunsigned? - →Which warning flags make GCC and Clang report that
i >= 0is always true here?