Monday 22 July 2019

Kotlin : Control Flow (Post 3)

Hi All,

In previous post , I have shared some basics overview of variables , datatypes , arrays etc.
Now in this post we will go through , the control flows : if-else, for loop etc.

if-else:

val a : Int = 5
val b : Int = 3
var max : Int = 0

if(a>b){
max = a
}else{
max = b
}

println("Maximum of a or b is " +max)

Output: Maximum of a or b is 5


When-Else

val x : Int = 1

when(x){
1-> println("x is 1")
2-> println("x is 2")
3-> println("x is 3")
else -> {
println("x is not 1 , 2 or 3")
}
}


Output: x is 1

For-Loop: 

    print("for (i in 1..5) print(i) = ")
    for (i in 1..5) print(i)
    println()
    
    print("for (i in 5..1) print(i) = ")
    for (i in 5..1) print(i)             // prints nothing
    println()
    
    print("for (i in 5 downTo 1) print(i) = ")
    for (i in 5 downTo 1) print(i)
    println()
    
    print("for (i in 1..5 step 2) print(i) = ")
    for (i in 1..5 step 2) print(i)
    println()
    
    print("for (i in 5 downTo 1 step 2) print(i) = ")
    for (i in 5 downTo 1 step 2) print(i)

Output:
for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) = 
for (i in 5 downTo 1) print(i) = 54321
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531

While Loop:
var x:Int = 0
println("Example of While Loop--")

while(x<=5){
println(x)
x++
}


Output:
0
1
2
3
4
5

That's it for this post , in next post I will share how we will write classes and objects etc. 

No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...