Control flow

Control flow statements determine the order in which code is executed.

if expression

Executes a block of code when a condition is true

if (condition) { //Block of code to be executed if the condition is true } else { //Block of code to be executed if the condition is false }

Example

val x = 1 val y = 5 if (x >= y) { println("x is greater than or equal to y") } else { println("x is smaller than y") } //>> x is smaller than y

while loop

Executes a block of code while a condition is true

while (condition) { //Block of code to be executed if the condition is true }

Example

var x = 1 val y = 5 while (x < y) { println(x) x += 1 } //>> 1 //>> 2 //>> 3 //>> 4

for loop

Use a for loop when the number of iterations is known.

The default variableName is set to val and is a temporary variable.

for (variableName in start..end) { //Block of code to be executed if the condition is true }

Example

for (i in 0..2) { println(i) } //variable i won't exist outside the for statement //>> 0 //>> 1 //>> 2

You can also use an existing variable instead of declaring a new one

for (tempVariable in start..end) { //Block of code to be executed if the condition is true }

Example

var i = 5 for (i in 0..2) { println(i) } println(i) //>> 0 //>> 1 //>> 2 //>> 3

If you want loop until end, you can use ..<

for (variableName in start..<end) { //Block of code to be executed if the condition is true } for (variableName in start..<end) { //Block of code to be executed if the condition is true }

Example

for (i in 0..<2) { println(i) } //>> 0 //>> 1

If you want loop until end, you can use ..<

break and continue

Sometimes, you want to skip or break a loop, you can use continue or break

Example continue

for (i in 0..2) { if (i == 1) { continue //Skip } println(i) } //>> 0 //>> 2

Example break

for (i in 0..2) { if (i == 1) { break //Break } println(i) } //>> 0