In this part, let us discuss the Control Flow of Kotlin programming language.
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.
- if (Condition) {
- //First branch statements
- } else {
- //First branch statements
- }
Syntax
- fun main(args: Array < String > ) {
- var n: Int = 5
- if (n % 2 == 0) {
- println("Even number.")
- } else {
- print("odd number.")
- }
- }
- //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.
- If(condition) {
- If(condition) {} else {}
- } else {}
Syntax
- fun main(args: Array < String > ) {
- var age: Int = 20
- var marks: Float = 65.50 f
- if (age in 20. .30) { //if(age>=20 && age<=30)
- if (marks >= 55.00 f) {
- println("Valid Candidate")
- } else {
- println("aggregate marks should greater than or equal to 55%")
- }
- } else {
- println("Age is over")
- }
- //output : Valid Candidate
- }
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.
- fun main(args: Array < String > ) {
- var a: Int = 5
- var b: Int = 15
- var c: Int = 3
- if (a > b && a > c) {
- println("a is biggest")
- } else if (b > c) {
- println("b is biggest")
- } else {
- println("c is biggest")
- }
- }
- //output : b is biggest
- If(condition) { //statements
- } else if (condition) { //statement
- }
- else {
- //statement
- }
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
- When(value) { < case1 > - > < statement > < case2 > - > < statement > < case3 > - > < statement >
- else - > < statement >
- }
Example
Write a Kotlin program to print a person's favorite color.
- fun main(args: Array < String > ) {
- var colorcode: Int = 2
- when(colorcode) {
- 1 - > println("your favorite color is RED")
- 2 - > println("your favorite color is GREEN")
- 3 - > println("your favorite color is YELLOW")
- else - > println("please choose a valid no. from 1-3")
- }
- }
- //output : your favorite color is GREEN

Join the conversation! Your thoughts help the community grow.