Kotlin Tutorial
Kotlin Classes
Loops:
Whenever we want to repeat a block of code; we use loops.
Loops are where the programming gets more interesting. Let’s suppose, you want to print a line 10 times; what will you do? Newbies would say this is so easy we will use print() function 10 times and our job is done. But what if you want to print a line a thousand times; you will use print() or println() thousand times will you?. There comes the Loops.
In all programming languages we have 2 types of loops that are:
- while / do while
- for
Each loop has different behavior.
While & do-while loops:
The only difference between while and do-while loop is:
- while loop check the condition first, if satisfied, execute the body and return to the condition again.
- do-while execute the body first then check the condition, if satisfied, return to the body execution again.
The loop terminates itself; when the condition becomes false.
While loop:
Syntax
while (condition) {
// block of code to be executed
}
Example:
var number = 0;
while (number < 5) {
println(number)
number++
}
The code above outputs:
0
1
2
3
4
Example explained:
In the example above the loop runs 5 times; and each time while executing the body it increments to the variable number, So first time the condition was if (0 < 5) then print the number and increment to the number variable; and second time the condition was if (1 < 5) print that number respectively. At the end when the condition comes in place if (5 < 5) the loop terminates itself because 5 is not less than 5.
Note: Don’t forget to increment number (number++) otherwise the loop will like **Im unstoppable I’m a Porsche with no brakes 😄** meaning loop will never end.
Do While loop:
Syntax
do {
// block of code to be executed
} while (condition)
Example:
var number = 0;
do {
println(number)
number ++
} while (number < 5)
The code above outputs:
0
1
2
3
4
The only difference is while loop checks the condition first and then executes the body while the do-while loop executes the body first and then checks the condition.