Bird
0
0

Why does the Kotlin loop for (i in 10 downTo 1 step 3) print 10, 7, 4, 1 instead of 10, 7, 4?

hard📝 Conceptual Q10 of 15
Kotlin - Loops and Ranges
Why does the Kotlin loop for (i in 10 downTo 1 step 3) print 10, 7, 4, 1 instead of 10, 7, 4?
ABecause downTo always prints one extra iteration.
BBecause step 3 skips the last value incorrectly.
CBecause the loop includes the end value if it matches the step sequence.
DBecause the loop variable increments instead of decrements.
Step-by-Step Solution
Solution:
  1. Step 1: Understand how downTo with step works

    The loop starts at 10 and subtracts 3 each time: 10, 7, 4, 1.
  2. Step 2: Recognize inclusion of end value

    The loop includes the end value 1 because it fits exactly in the stepping sequence.
  3. Final Answer:

    Because the loop includes the end value if it matches the step sequence. -> Option C
  4. Quick Check:

    Loop includes end if reachable by step [OK]
Quick Trick: Loop includes end if step lands exactly on it [OK]
Common Mistakes:
MISTAKES
  • Thinking loop stops before end value
  • Assuming extra iteration is error
  • Confusing increment with decrement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes