Welcome to the fourth tutorial of our Kotlin course! In this tutorial, we’ll explore control flow structures in Kotlin. Control flow structures allow us to make decisions and repeat code based on specific conditions. We’ll cover conditional statements (if, else) and loops (for, while) in Kotlin.
Conditional Statements: if and else
Conditional statements are used to execute specific blocks of code based on certain conditions. In Kotlin, we have the if and else statements to handle conditional logic. Conditional statements are used to make decisions in your code. The most common conditional statement in Kotlin is the if statement. The if statement has the following syntax:
The basic syntax of the if statement is as follows:
1 2 3 4 5 |
if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false } |
Here’s an example that demonstrates the usage of if and else statements:
1 2 3 4 5 6 7 8 9 10 |
fun main() { val number = 10 if (number > 0) { println("The number is positive") } else { println("The number is negative or zero") } } |
In the above code, if the number variable is greater than 0, it prints “The number is positive.” Otherwise, it prints “The number is negative or zero.”
Look at another example inthe following code.
1 2 3 4 5 6 7 8 |
val number = 10 if (number % 2 == 0) { println("The number is even") } else { println("The number is odd") } |
In the preceding code, it will print “The number is even” if the number is even, and “The number is odd” if the number is odd.
Furthermore, the preceding code uses the % operator.
The % operator in many programming languages, including Kotlin, is called the modulus operator. It is used to perform the modulo operation, which calculates the remainder when one number is divided by another.
The syntax of the % operator is as follows:
1 |
dividend % divisor |
Here, the dividend is the number that is being divided, and the divisor is the number that is dividing the dividend.
For example, let’s consider the expression 10 % 3. In this case, 10 is the dividend, and 3 is the divisor. When 10 is divided by 3, it results in a quotient of 3 with a remainder of 1. Therefore, the expression 10 % 3 evaluates to 1.
Similarly, if we have an expression like 17 % 5, the dividend is 17 and the divisor is 5. When 17 is divided by 5, it results in a quotient of 3 with a remainder of 2. So, the expression 17 % 5 evaluates to 2.
The modulus operator is often used in programming to perform operations where the remainder is important. For example, it can be used to determine whether a number is even or odd or to wrap values within a specific range.
Here’s an example that demonstrates the usage of the modulus operator in Kotlin:
1 2 3 4 5 6 7 8 9 10 |
fun main() { val number = 27 if (number % 2 == 0) { println("The number is even") } else { println("The number is odd") } } |
In the above code, we use the % operator to check if the number is divisible evenly by 2. If the remainder is 0, it means the number is even. Otherwise, it is odd.
Overall, the modulus operator provides a convenient way to work with remainders in mathematical and programming operations. It can be useful in a variety of scenarios, such as determining divisibility, cycling through values, or implementing specific behaviors based on remainders.
You can also use multiple if statements in a row like in this next sample.
1 2 3 4 5 6 7 8 9 10 11 12 |
val number = 0 if (number > 0) { println("The number is positive") } else if (number < 0) { println("The number is negative") } else { println("The number is zero") } |
In the preceding code, it will print “The number is positive” if the number is greater than 0, “The number is negative” if the number is less than 0, and “The number is zero” if the number is equal to 0:
Loops: for
Loops allow us to repeat a block of code multiple times until a certain condition is met. Kotlin provides two types of loops: for and while.
The for loop is used when we know the number of iterations in advance. The basic syntax of the for loop is as follows:
1 2 3 |
for (item in collection) { // Code to execute for each item in the collection } |
Here’s an example that demonstrates the usage of a for loop:
1 2 3 4 5 6 7 |
fun main() { val numbers = arrayOf(1, 2, 3, 4, 5) for (number in numbers) { println(number) } } |
In the above code, the for loop iterates over each element in the numbers array and prints it.
The for loop can have many different shorthand syntaxes. This is a huge time saver for Kotlin programmers but it takes practice to learn all the diffeerent syntaxes. For example, the following code will print the numbers from 1 to 10:
1 2 3 4 |
val numbers = 1..10 for (number in numbers) { println(number) } |
Let’s move on to while loops.
Loops: while
The while loop is used when we want to repeat a block of code until a certain condition is no longer true. The basic syntax of the while loop is as follows:
1 2 3 |
while (condition) { // Code to execute as long as the condition is true } |
Here’s a real example that demonstrates the usage of a while loop:
1 2 3 4 5 6 7 8 |
fun main() { var count = 0 while (count < 5) { println("Count: $count") count++ } } |
In the above code, the while loop prints the value of count until it reaches 5.
As we have seen, the while loop executes the code block as long as the condition is true. Here is another example:
1 2 3 4 5 6 7 8 9 10 |
var number = 1 while (number >= 0) { println(number) println("Enter a number: ") val input = readLine()!!.toInt() number = input } |
In the preceding code, it will print the numbers from 1 to 10, but will stop if the user enters a negative number.
There are two more Kotlin keywords that we can discuss which can be used in conjunction with loops.
Break and Continue
The break statement can be used to exit a loop early. For example, the following code will print the numbers from 1 to 10, but will stop if the user enters a negative number:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var number = 1 while (number >= 0) { println(number) println("Enter a number: ") val input = readLine()!!.toInt() if (input < 0) { break } number = input } |
The continue statement can be used to skip the rest of the current iteration of a loop. For example, the following code will print all the even numbers from 1 to 10:
1 2 3 4 5 6 7 |
for (number in 1..10) { if (number % 2 == 1) { continue } println(number) } |
Break and continue are great for solving logic problems. If you are planning a loop and something just doesn’t seem possible, consider using break or continue.
Summary
In this tutorial, we explored control flow structures in Kotlin. We learned how to use conditional statements (if and else) to make decisions based on specific conditions. We also covered loops (for and while) to repeat code until a certain condition is met.
Control flow structures are fundamental in programming as they enable us to create dynamic and flexible logic in our code. Understanding how to make decisions and repeat code based on conditions is essential for building robust and efficient programs.
You can use these structures to make decisions and repeat code in your programs.
In the next tutorial, we’ll delve into functions in Kotlin, which allow us to encapsulate reusable blocks of code. If you have any questions or need further clarification, feel free to ask. Keep up the great work, and let’s continue exploring Kotlin together!
Leave A Comment