Kotlin Control Flow

In this part, let us discuss the Control Flow of Kotlin programming language.

Control Flow

If-Else Expression

It is used for conditional branching of the statements. The first branch will execute when a condition is true, otherwise, the statements of the second branch will execute.

  1. if (Condition) {  
  2.     //First branch statements  
  3. else {  
  4.     //First branch statements              

Syntax

  1. fun main(args: Array < String > ) {  
  2.     var n: Int = 5  
  3.     if (n % 2 == 0) {  
  4.         println("Even number.")  
  5.     } else {  
  6.         print("odd number.")  
  7.     }  
  8. }  
  9. //output is -  odd number.  

Example

Kotlin program to check if an input number is even or odd.

Nested If-else Expression

If within "If" is known as "nested if" expression.

  1. If(condition) {  
  2.     If(condition) {} else {}  
  3. else {}  

Syntax         

  1. fun main(args: Array < String > ) {  
  2.     var age: Int = 20  
  3.     var marks: Float = 65.50 f  
  4.     if (age in 20. .30) { //if(age>=20 && age<=30)  
  5.         if (marks >= 55.00 f) {  
  6.             println("Valid Candidate")  
  7.         } else {  
  8.             println("aggregate marks should greater than or equal to 55%")  
  9.         }  
  10.     } else {  
  11.         println("Age is over")  
  12.     }  
  13.     //output :  Valid Candidate  
  14. }  

Example

Write a Kotlin program to check if the candidate is eligible for Bank PO exam or not (where the age limit is 20-30 and minimum aggregate marks in graduation should be 55%).

If-else ladder

Example

Write a program to find the biggest among 3 numbers.

  1. fun main(args: Array < String > ) {  
  2.     var a: Int = 5  
  3.     var b: Int = 15  
  4.     var c: Int = 3  
  5.     if (a > b && a > c) {  
  6.         println("a is biggest")  
  7.     } else if (b > c) {  
  8.         println("b is biggest")  
  9.     } else {  
  10.         println("c is biggest")  
  11.     }  
  12. }  
  13. //output : b is biggest  
Syntax
  1. If(condition) { //statements  
  2. else if (condition) { //statement  
  3. }  
  4. else {  
  5.     //statement  
  6. }  

When Expression

It is used to execute multiple conditional statements of If-Else in a single place. It is a replacement for the Switch Expression used in C, C++, and Java programming languages.

Syntax

  1. When(value) { < case1 > - > < statement > < case2 > - > < statement > < case3 > - > < statement >  
  2.         else - > < statement >  

Example

Write a Kotlin program to print a person's favorite color.                                                                  

  1. fun main(args: Array < String > ) {  
  2.     var colorcode: Int = 2  
  3.     when(colorcode) {  
  4.         1 - > println("your favorite color is RED")  
  5.         2 - > println("your favorite color is GREEN")  
  6.         3 - > println("your favorite color is YELLOW")  
  7.         else - > println("please choose a valid no. from 1-3")  
  8.     }  
  9. }  
  10. //output : your favorite color is GREEN           

While loop

It first of all checks the given condition. If the condition is true, then it executes the body statements otherwise, exits from the loop.

Syntax

  1. While(condition) {  
  2.     //body statement  
  3. }  
Example

Write a program to print Natural Numbers.
  1. fun main(args: Array < String > ) {  
  2.     var naturalnum: Int = 1  
  3.     while (naturalnum <= 9) {  
  4.         print(" " + naturalnum)  
  5.         naturalnum++  
  6.     }  
  7. }  
  8. //output: 1 2 3 4 5 6 7 8 9  

Do While loop

It first of all executes the body statement once, then checks the condition of the While loop to execute the statement for next time.

Syntax

  1. do {  
  2.     //body statement  
  3. while (condition)  
Example

Write a program to print the table of 2.
  1. fun main(args: Array < String > ) {  
  2.     var table: Int = 2  
  3.     do {  
  4.         print(" " + table)  
  5.         table = table + 2  
  6.     } while (table <= 20)  
  7. }  
  8. //Output: 2 4 6 8 10 12 14 16 18 20  

For Each loop

It is used to fetch the data one by one from a collection. The loop will execute until whole elements of the collection are processed or the loop is terminated.

Syntax

  1. for ( < variablename > in collection) {  
  2.     //body statement  
  3. }  

Example

Write a program to print the days of a week.                                                                    

  1. import com.sun.xml.internal.fastinfoset.util.StringArray  
  2. fun main(args: Array < String > ) {  
  3.     var week = arrayOf("Monday""Tuesday""Wednesday""Thursday""Friday""Saturday""Sunday")  
  4.     for (day in week) {  
  5.         print(" " + day)  
  6.     }  
  7. //output: Monday Tuesday Wednesday Thursday Friday Saturday Sunday  

Return and Jump

There are three structural Jump expressions in Kotlin.

  1. return. By default, it returns value from the nearest enclosing function or anonymous function.
  2. break. Terminates the nearest enclosing loop.
  3. continue. Proceeds to the next step of the nearest enclosing loop.

    return Expression
    val s = person.name ?: return 

    The type of these expressions is the Nothing type.
  • You can use any expression or identifier to create a label.To create the label, you have to use @ notation after the label name, i.e., label@ and you can use @label to go to this label. Let's see with an example.

    Return to label
    1. fun myfun() {  
    2.     ints.forEach label @ {  
    3.         if (it == 0) return @label  
    4.         print(it)  
    5.     }  
    6. }  

Break and Continue

Continue proceeds the control for next execution of the loop while Break exits the control from the body of the loop.

  1. Loop(condition) { //body  
  2.     If(condition) {  
  3.         //statement  
  4.         continue  
  5.     } else {  
  6.         break  
  7.     }  
  8. }  

Example

Write a program to check if a number is a prime number or not. (Prime numbers are those number which can be divided only by 1 or itself). 

  1. fun main(args:Array<String>){  
  2.     var num:Int=7  
  3.     var i:Int=2  
  4.     var count:Int=0  
  5.     while(i<num){  
  6.         if(num%i==0)  
  7.         {  
  8.             count=1  
  9.             println("Not prime")  
  10.             break  
  11.         }else  
  12.         {  
  13.             i++  
  14.             continue  
  15.         }  
  16.     }  
  17.     if(count==0)  
  18.     {  
  19.         println("Prime")  
  20.     }  
  21. }  

Up Next
    Ebook Download
    View all
    Learn
    View all