Bird
0
0

What is the output of the following Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Loops and Ranges
What is the output of the following Kotlin code?
for (i in 8 downTo 2 step 3) {
    print("$i ")
}
A8 5 2
B8 6 4 2
C8 5 3
D8 5 2 1
Step-by-Step Solution
Solution:
  1. Step 1: Determine the loop values

    The loop starts at 8, counts down to 2, stepping by 3. So values are 8, then 8-3=5, then 5-3=2.
  2. Step 2: Confirm the loop stops at 2

    Since 2 is the end value and included, the loop prints 8, 5, and 2.
  3. Final Answer:

    8 5 2 -> Option A
  4. Quick Check:

    8, 5, 2 with step 3 downTo 2 = 8 5 2 [OK]
Quick Trick: Subtract step each time, stop at end value [OK]
Common Mistakes:
MISTAKES
  • Including numbers less than end value
  • Using wrong step size
  • Confusing downTo with ..

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes