Motivation
This article is written for more advanced developers which are looking to get a quick grasp on the Kotlin Language for work or for some interesting projects.
In this article, we cover loops and exceptions and how to best use them. This is part 3 in a longer series.
Part 1 : Getting Started with Kotlin
Part 2 : Control Flow in Kotlin
Part 3 : Loops and Exceptions in Kotlin
Part 4 : Working with Types in Kotlin ( Coming Soon )
While Loops
While loops follow a general syntax of
while (Boolean Expression is true){
//Perform some action
}
At each iteration, Kotlin checks to see if the boolean expression is still true. If it is, then it continues iterating through the block.
Note : This means that if your condition is not true, your loop will never run
We can see an example of this below
fun main(){
val repetitions = 10;
var counter = 0
while(counter < repetitions){
println("Counter : $counter ")
counter++
}
}
which gives us the output of
Counter : 0
Counter : 1
Counter : 2
Counter : 3
Counter : 4
Counter : 5
Counter : 6
Counter : 7
Counter : 8
Counter : 9
Do-While
If you want your loop to run at least once, a do-while
loop is what you'll probably want to use.
do{
// Perform some action
} while(Boolean Expression is true)
We can rewrite the while loop above into a do-while as
fun main(){
val repetitions = 10;
var counter = 0
do{
println("Counter : $counter ")
counter++
}while(counter < repetitions)
}
Note : This means that if your condition is not true, your loop will run at least once
We can verify that our do while loop runs at least once using the code-snippet below
fun main(){
val condition = false
do{
println("Loop Ran")
}while(condition)
}
For-Loops
We can also use For-Loops
if we have a known-number of iterations that we want to execute our blocks of code for.
The general syntax is
for(x in something){
//Do Something
}
There are two main ways that we can work with for loops - using repeat
or with ranges
Repeat
The repeat
function call allows us to perform an action a set number of times.
fun main(){
repeat(3){
println("Loop Ran")
}
}
Which gives the output of
Loop Ran
Loop Ran
Loop Ran
Ranges
We can see a more concrete example below using ranges with
fun main(){
val range = 3..5
for(i in range){
println(i)
}
}
Note :
3..5
is a shorthand syntax which we use to generate a range. So in this case,3..5
is equivalent to a range with the values3,4,5
.
We can generate the same range in different ways as seen below
3..5
3 until 5
3..5 step 1
We can also generate ranges that go in the reverse direction (eg. 5,4,3 )
5 downTo 3 step 1
Note : Ranges can also be used for characters (Eg. "a","b","c" which can be generated by
'a'..'c'
)
Top comments (0)