Kotlin - Control Expression, Loop Structure, Return And Jump

Introduction

 
In this part, we are going to learn about Control Expression, Loop Structure, Return, and Jump. Those who would like to learn about Kotlin, the pros and cons of Kotlin, Kotlin variables and datatypes, Kotlin operators and comments, should click the links below.

Kotin Control Expression

 
It is used for controlling the flow of the program structure. In Kotlin, it is an expression which returns a value.
 
The list of Expressions are,
  • if-else Expression
  • if else if else Expression
  • Nested if Expression
  • When Expression

Kotlin if else Expression

 
In Kotlin “if” is an expression, it is not a keyword. The expression “if” will return a value whenever necessary. Like other programming languages, the “if-else” block is used as an initial conditional checking operator, and the result of an if-else expression is assigned into a variable.
 
Syntax
  1. val returnValue = if (condition) {    
  2.      //code statement    
  3.     } else {    
  4.      // code statement    
  5.     }    
  6.     println(return Value)  
Example
  1. fun main(args: Array<String>) {  
  2.    val a:Int = 5  
  3.    val b:Int = 2  
  4.    var max: Int  
  5.      
  6.    if (a > b) {  
  7.       max = a  
  8.    } else {  
  9.       max = b  
  10.    }  
  11.    print("Maximum of a or b is " +max)  
  12.    
  13.    // As expression   
  14.    // val max = if (a > b) a else b  
  15. }  
Output
 
Maximum of a or b is 5
 
Kotlin - Control Expression, Loop Structure, Return And Jump
 

Kotlin- if elseif else Expression

 
We can return a block of code among many blocks in Kotlin using if..elseif..else ladder
 
Example 
  1. fun main(args: Array<String>) {    
  2.     val num = 10    
  3.     val result = if (num > 0){    
  4.         "$num is positive"    
  5.     }else if(num < 0){    
  6.         "$num is negative"    
  7.     }else{    
  8.         "$num is zero"    
  9.     }    
  10.     println(result)    
  11. }   
Output
 
10 is positive
 

Kotlin - Nested if Expression

 
A nested if statement is an if-else statement with another if statement as the if body or the else body evaluates the condition of the outer if.
 
If it evaluates to false, don't run the code in the if body.  Nested if in Kotlin basically evaluates the outer condition, and only when it succeeds does it evaluate the inner condition.
 
Example 
  1. fun main(args: Array<String>) {    
  2.     val num1 = 25    
  3.     val num2 = 20    
  4.     val num3 = 30    
  5.     val result = if (num1 > num2){    
  6.     
  7.         val max = if(num1 > num3){    
  8.             num1    
  9.         }else{    
  10.             num3    
  11.         }    
  12.         "body of if "+max    
  13.     }else if(num2 > num3){    
  14.         "body of else if"+num2    
  15.     }else{    
  16.         "body of else "+num3    
  17.     }    
  18.     println("$result")    
  19. }   
Output
 
body of if 30
 

Kotlin - When Expression

 
If you are familiar with other programming languages, then you might have heard of the term switch statement, which is basically a conditional operator when multiple conditions can be applied on a particular variable. “when” operator matches the variable value against the branch conditions. If it is satisfying the branch condition then it will execute the statement inside that scope in Kotlin, when expression works as a switch statement of other language (Java, C++, C).
 
Example 
  1. fun main(args: Array<String>) {  
  2.   
  3.     val value1 = 90  
  4.     val value2 = 6  
  5.   
  6.     println("Enter operator either +, -, * or /")  
  7.     var operator = readLine()  
  8.   
  9.     val result = when (operator) {  
  10.         "+" -> value1 + value2  
  11.         "-" -> value1 - value2  
  12.         "*" -> value1 * value2  
  13.         "/" -> value1 / value2  
  14.         else -> "$operator operator is invalid operator."  
  15.     }  
  16.   
  17.     println("result = $result")  
  18.   
  19.     val a = 100  
  20.     val b = 6  
  21.   
  22.     println("Enter operator either +, -, * or /")  
  23.   
  24.     operator = readLine()  
  25.   
  26.     when (operator) {  
  27.         "+" -> println("$a + $b = ${a + b}")  
  28.         "-" -> println("$a - $b = ${a - b}")  
  29.         "*" -> println("$a * $b = ${a * b}")  
  30.         "/" -> println("$a / $b = ${a / b}")  
  31.         else -> println("$operator is invalid")  
  32.     }  
  33. }  
Output
 
Enter operator either +, -, * or /
/
result = 15
Enter operator either +, -, * or /
*
100 * 6 = 600
 

Loop Structure

 

Kotlin - For Loop

 
Like other programming languages, Kotlin also provides many kinds of Looping methodologies, however, among them “For” is the most successful one. The implementation and the use of For loop is conceptually similar to Java For loop. Kotlin For loop is used to iterate a part of the program several times. It iterates through arrays, ranges, collections, or anything that provides for iterate. Kotlin for loop is equivalent to the foreach loop in languages like C#.
 
Syntax 
  1. for (item in collection){    
  2. //body of loop    
  3. }   
Example
  1. fun main(args : Array<String>) {    
  2.        
  3.     val marks = arrayOf(80,85,60,90,70)    
  4.     for(item in marks.indices)    
  5.        println("marks[$item]: "+ marks[item])    
  6. }    
Output
 
marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70
 

Kotlin - While Loop

 
As like In Java, Kotlin while loop continually executes a block of statements while a particular condition is true.Test expression inside the while loop parenthesis is a Boolean expression.If the test expression is evaluated to true then contents inside the while loop will be executed. Process continues until the test expression is evaluated to false. If the test expression is evaluated to false while will terminate it's execution.
 
Syntax
  1. while(condition){    
  2. //body of loop    
  3. }    
Example
  1. fun main(args: Array<String>) {  
  2.    var x:Int = 0  
  3.    println("Example of While Loop--")  
  4.      
  5.    while(x< = 10) {  
  6.       println(x)  
  7.       x++  
  8.    }   
  9. }  
Output
 
Example of While Loop,
 
0
1
2
3
4
5
6
7
8
9
10
 

Kotlin - Do While

 
The do-while loop is similar to while loop except one key difference. A do-while loop first executes the body of do block, after that it checks the condition of while. As a do block of do-while loop is executed first before checking the condition, do-while loop executes at least once even the condition within while is false. The while statement of do-while loop ends with ";" (semicolon).
 
Syntax
  1. do{    
  2.    //body of do block    
  3. }    
  4. while(condition);    
Example
  1. fun main(args: Array<String>){    
  2.     var i = 1    
  3.     do {    
  4.         println(i)    
  5.         i++    
  6.     }    
  7.     while (i<=5);    
  8. }   
Output
 
1
2
3
4
5
 

Kotlin - Return

 
Return is a keyword that returns some value to the calling function from the called function.
 
Example
  1. fun main(args: Array<String>) {  
  2.    var x:Int = 10  
  3.    println("The value of X is--"+doubleMe(x))  
  4. }  
  5. fun doubleMe(x:Int):Int {  
  6.    return 2*x;  
  7. }  
Output
 
The value of X is—20
 

Kotlin - Continue

 
Like every programming language, in Kotlin also, the continue expression skips the current iteration of the enclosing loop and the control of the program jumps to the end of the loop body. In the above program if the value of i is greater than three and less than five the continue expression is called and control returns back to the loop body. Continue statement is used to stop the execution of the body and control goes back to the next iteration.
 
Example
  1. fun main(args: Array<String>) {    
  2.         for (i in 1..3) {    
  3.             println("i = $i")    
  4.             if (j == 2) {    
  5.                 continue    
  6.             }    
  7.             println("this is below if")    
  8.         }    
  9. }  
Output
 
i = 1
this is below if
i = 2
i = 3
this is below if
 

Kotlin - Break 

 
A break expression is used for terminating the nearest enclosing loop. It is almost used with the if-else condition.
 
Example
  1. fun main(args: Array<String>) {    
  2.     for (i in 1..5) {    
  3.         if (i == 3) {    
  4.             break    
  5.         }    
  6.         println(i)    
  7.     }    
  8. }  
Output
 
1
2
 

Conclusion

 
In this article, we learned various control statements and loops in Kotlin. In the next part, we will learn about Kotlin Functions, Recursion Functions and Lambda Functions.
 
Next in this series: Kotlin Functions


Similar Articles