Difficulty: Medium
Correct Answer: 4, 3, 2, 1, 0, -1 4, 3, 2, 1, 0, -1
Explanation:
Introduction / Context:
This problem focuses on how i--
behaves in a loop condition and how the variable's value changes before the body executes. It also contrasts two loops separated by a reset and a newline, then shows that a final loop may not execute at all.
Given Data / Assumptions:
i = 5
.i-- >= 0
compares first, then decrements.i
.
Concept / Approach:
When the condition is i-- >= 0
, the comparison uses the old value of i
, then i
is decremented before entering the body. Consequently, the printed sequence is one less than the value checked in the condition. The loop runs while the old value is at least 0, producing a sequence down to −1 in the output.
Step-by-Step Solution:
%i
(same as %d
) producing 4, 3, 2, 1, 0, -1
.Third loop: after the second loop, i
is −1; condition i-- >= 0
is false at once; no output.
Verification / Alternative check:
Change the condition to --i >= 0
or i >= 0
with a separate decrement to see how the printed values shift.
Why Other Options Are Wrong:
--i
in the body or a different condition; not the case here.Error/No output: the program is valid and clearly prints two sequences.
Common Pitfalls:
Forgetting the difference between pre- and post-decrement; assuming %i
and %d
differ for int
(they do not).
Final Answer:
4, 3, 2, 1, 0, -1 4, 3, 2, 1, 0, -1.
switch
statement in C? Note the statement before any case
label.
#include
Discussion & Comments