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
- val returnValue = if (condition) {
-
- } else {
-
- }
- println(return Value)
Example
- fun main(args: Array<String>) {
- val a:Int = 5
- val b:Int = 2
- var max: Int
-
- if (a > b) {
- max = a
- } else {
- max = b
- }
- print("Maximum of a or b is " +max)
-
-
-
- }
Output
Maximum of a or b is 5
Kotlin- if elseif else Expression
We can return a block of code among many blocks in Kotlin using if..elseif..else ladder
Example
- fun main(args: Array<String>) {
- val num = 10
- val result = if (num > 0){
- "$num is positive"
- }else if(num < 0){
- "$num is negative"
- }else{
- "$num is zero"
- }
- println(result)
- }
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
- fun main(args: Array<String>) {
- val num1 = 25
- val num2 = 20
- val num3 = 30
- val result = if (num1 > num2){
-
- val max = if(num1 > num3){
- num1
- }else{
- num3
- }
- "body of if "+max
- }else if(num2 > num3){
- "body of else if"+num2
- }else{
- "body of else "+num3
- }
- println("$result")
- }
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
- fun main(args: Array<String>) {
-
- val value1 = 90
- val value2 = 6
-
- println("Enter operator either +, -, * or /")
- var operator = readLine()
-
- val result = when (operator) {
- "+" -> value1 + value2
- "-" -> value1 - value2
- "*" -> value1 * value2
- "/" -> value1 / value2
- else -> "$operator operator is invalid operator."
- }
-
- println("result = $result")
-
- val a = 100
- val b = 6
-
- println("Enter operator either +, -, * or /")
-
- operator = readLine()
-
- when (operator) {
- "+" -> println("$a + $b = ${a + b}")
- "-" -> println("$a - $b = ${a - b}")
- "*" -> println("$a * $b = ${a * b}")
- "/" -> println("$a / $b = ${a / b}")
- else -> println("$operator is invalid")
- }
- }
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
- for (item in collection){
-
- }
Example
- fun main(args : Array<String>) {
-
- val marks = arrayOf(80,85,60,90,70)
- for(item in marks.indices)
- println("marks[$item]: "+ marks[item])
- }
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
Example
- fun main(args: Array<String>) {
- var x:Int = 0
- println("Example of While Loop--")
-
- while(x< = 10) {
- println(x)
- x++
- }
- }
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
Example
- fun main(args: Array<String>){
- var i = 1
- do {
- println(i)
- i++
- }
- while (i<=5);
- }
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
- fun main(args: Array<String>) {
- var x:Int = 10
- println("The value of X is--"+doubleMe(x))
- }
- fun doubleMe(x:Int):Int {
- return 2*x;
- }
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
- fun main(args: Array<String>) {
- for (i in 1..3) {
- println("i = $i")
- if (j == 2) {
- continue
- }
- println("this is below if")
- }
- }
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
- fun main(args: Array<String>) {
- for (i in 1..5) {
- if (i == 3) {
- break
- }
- println(i)
- }
- }
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.