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

while loops


Kotlin while loops have the simplest syntax. Think back to the if statements for a moment; we could use virtually any combination of operators and variables in the conditional expression of the if statement. If the expression evaluated to true, then the code in the body of the if block is executed. With the while loop, we also use an expression that can evaluate to true or false:

var x = 10

while(x > 0) {
  Log.i("x=", "$x")
  x--
}

Take a look at the preceding code; what happens here is as follows:

  1. Outside of the while loop, an Int type named x is declared and initialized to 10.

  2. Then, the while loop begins; its condition is x > 0. So, the while loop will execute the code in its body.

  3. The code in its body will repeatedly execute until the condition evaluates to false.

So, the preceding code will execute 10 times.

On the first pass, x equals 10 on the second pass it equals 9, then 8, and so on. But once x is equal to 0, it is, of course, no longer greater than 0. At this point...

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