Reader small image

You're reading from  Android Programming with Kotlin for Beginners

Product typeBook
Published inApr 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789615401
Edition1st Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton

Right arrow

do-while loops


The dowhile loop works in the same way as the ordinary while loop except that the presence of a do block guarantees that the code will execute at least once, even when the condition of the while expression does not evaluate to true:

var y = 10
do {
  y++
  Log.i("In the do block and y=","$y")
}
while(y < 10)

If you copy and paste this code into one of your apps in the onCreate function, and then execute it, the output might not be what you expect. Here is the output:

In the do block and y=: 11

This is a less-used but sometimes perfect solution for a problem. Even though the condition of the while loop is false, the do block executes its code, increments the y variable to 11, and prints a message to logcat. The condition of the while loop is y < 10, so the code in the do block is not executed again. If the expression in the while condition is true, however, then the code in the do block continues to execute as though it was a regular while loop.

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Android Programming with Kotlin for Beginners
Published in: Apr 2019Publisher: PacktISBN-13: 9781789615401

Author (1)

author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton