+ 1
Kotlin While loop doubt
Hi guys, I'm new to coding plz help me to solve the following issue on while loop in kotlin Why following while loop prints 5 also as the last output even though i just asked while loop to print still the number is less than 5 so while loop should stop print at 4 right??? fun main(args: Array<String>) { var number = 0 while (number < 5) { number += 1 println(number) } } // output // 1 // 2 // 3 // 4 // 5
1 Answer
+ 1
When you increment number to 4 it then prints it and goes back to the while condition, sees that 4 is less than 5 and continues to the next code in the loop that then increments number to 5, prints it out and check the condition once again, seeing that its false and exits the loop.
Solution:
Initialize number as 1 and increment number after println()
fun main(args: Array<String>) {
var number = 1
while (number < 5) {
println(number)
number += 1
}
}