If-Else Statement

In this we will read how to use control flow expressions and statments. Conditional expressions like if, if-else, when and looping statements like for,while, do-while

If Statement

The If statement allows you to specify a section of code that is executed only if a given condition is true

package com.rrtutors.sample
fun main(args: Array) {
;val k=20;
if(k%2==0)
{ println("Kotlin If Statement")
}

if statement contains a single line then we can write condition in single line like below
  if(k%2==0) println("Kotlin If Statement")


The If Else statment execute one satement, if condition true if statement will execute, if condition false else statement will execute.


var a = 32
var b = 55

if(a > b) {
 println("max($a, $b) = $a")
} else {
 println("max($a, $b) = $b")
 }
 

When Expression

When expression is similor to switch statemen like in other langugaes

we can defin the when expression like below.

var a = 3
when(a)
{

    1-> println("one")

    2-> println("Two")

    3-> println("Three")

    else-> println("Else")

}



output : Three

each case statement we can also write aas block

when(a)
{

    1-> {

        println("one")

        println("1")

    }

    2-> {

        println("Two")

        println("2")

    }

    3-> {

        println("Three")

        println("3")

    }

    else-> {

        println("Else")

        println("Not a vlue")

    }

}

We can user when as expression.

var number = 4

var numberInString = when(dayOfWeek) {
    1 -> "One"
    2 -> "Two"
    3 -> "Three"
    4 -> "Four"
    5 -> "Five"
    6 -> "Six"
    7 -> "Seven"
    else -> "Invalid number"
}

println("Selected number is $numberInString ")


Output: Selected number is Four
Multiple conditions with when expression
var dayOfWeek = 4
when(dayOfWeek) {
    1, 2, 3, 4, 5 -> println("Weekday")
    6, 7 -> println("Weekend")
    else -> println("Invalid Day")
}

In operator with when expression. This will check when the given value is with in the range or not
var selectedNumber = 5
when(selectedNumber) {
    in 1..10 -> println("Selected value in between 1 to 10")
    !in 11..20 -> println("Selected value in between 11 to 20")
    else -> println("none of the above")
}

output : Selected value in between 1 to 10

While Loop

While loop will execute as long as condition staticfied
var k=7;
while(k>0)
{

    println(k)
    k--
}

do-while loop

Like while loop do-while will also execute the block until condition saticfied,
but do will execute every first time without condition check
  var k=2;
   do{
       println("Inside do "+k)
       k++
   }
   while(k<=1)

   Here the out put will print once with Inside do 2

   but when the while loop will not print any output

For Loop

For loop will used to iterate any values like arrays,ranges...
for (value in 1..5)
{
    println(value);
}

Output : 1
2
3
4
5
Iterating the array with for loop

le="margin-left:40px">val array=arrayOf(1,2,3,4,5)
for (k in array )
{
  println(k)
}