Bird
0
0

How can you modify this Kotlin code to ensure the loop runs at least once and prints numbers 1 to 5?

hard📝 Application Q9 of 15
Kotlin - Loops and Ranges
How can you modify this Kotlin code to ensure the loop runs at least once and prints numbers 1 to 5?
var count = 1
while (count <= 5) {
  println(count)
  count++
}
AAdd a print before the loop
BChange while to do-while and keep the rest same
CInitialize count to 0
DAdd a break inside the loop
Step-by-Step Solution
Solution:
  1. Step 1: Understand current loop behavior

    While loop runs only if condition true; here it runs from 1 to 5.
  2. Step 2: Guarantee at least one run

    Changing to do-while ensures the body runs once before condition check.
  3. Final Answer:

    Change while to do-while and keep the rest same -> Option B
  4. Quick Check:

    do-while runs body once before condition = A [OK]
Quick Trick: Switch to do-while for guaranteed first run [OK]
Common Mistakes:
MISTAKES
  • Adding print outside loop
  • Changing initial count wrongly
  • Using break incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes