In this section, we will explore how to control the flow of your Kotlin programs using conditionals and loops. These constructs allow you to make decisions and repeat actions, which are fundamental for creating dynamic and efficient code.
- Conditionals
If-Else Statements
The if
statement is used to execute a block of code if a specified condition is true. The else
statement can be used to execute a block of code if the condition is false.
Syntax:
if (condition) { // code to execute if condition is true } else { // code to execute if condition is false }
Example:
val number = 10 if (number > 0) { println("The number is positive.") } else { println("The number is not positive.") }
If-Else If-Else Ladder
When you have multiple conditions to check, you can use an if-else if-else
ladder.
Syntax:
if (condition1) { // code to execute if condition1 is true } else if (condition2) { // code to execute if condition2 is true } else { // code to execute if none of the above conditions are true }
Example:
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.") }
When Expression
The when
expression in Kotlin is a more powerful and flexible version of the switch
statement found in other languages.
Syntax:
when (value) { case1 -> { // code to execute if value matches case1 } case2 -> { // code to execute if value matches case2 } else -> { // code to execute if value doesn't match any case } }
Example:
val dayOfWeek = 3 val dayName = when (dayOfWeek) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6 -> "Saturday" 7 -> "Sunday" else -> "Invalid day" } println(dayName)
- Loops
For Loop
The for
loop is used to iterate over a range, array, or collection.
Syntax:
Example:
While Loop
The while
loop executes a block of code as long as a specified condition is true.
Syntax:
Example:
Do-While Loop
The do-while
loop is similar to the while
loop, but it guarantees that the block of code will be executed at least once.
Syntax:
Example:
Practical Exercises
Exercise 1: Even or Odd
Write a Kotlin program that checks if a number is even or odd.
Solution:
fun main() { val number = 4 if (number % 2 == 0) { println("$number is even.") } else { println("$number is odd.") } }
Exercise 2: Sum of First N Natural Numbers
Write a Kotlin program to calculate the sum of the first N natural numbers using a for
loop.
Solution:
fun main() { val n = 10 var sum = 0 for (i in 1..n) { sum += i } println("Sum of first $n natural numbers is $sum.") }
Exercise 3: Factorial of a Number
Write a Kotlin program to find the factorial of a number using a while
loop.
Solution:
fun main() { val number = 5 var factorial = 1 var i = number while (i > 0) { factorial *= i i-- } println("Factorial of $number is $factorial.") }
Common Mistakes and Tips
- Forgetting to update the loop variable: Ensure that the loop variable is updated within the loop to avoid infinite loops.
- Off-by-one errors: Be careful with the range boundaries in loops to avoid off-by-one errors.
- Using
when
withoutelse
: Always include anelse
branch in awhen
expression to handle unexpected values.
Conclusion
In this section, we covered the basics of controlling the flow of your Kotlin programs using conditionals and loops. We learned about if-else
statements, when
expressions, and different types of loops (for
, while
, and do-while
). These constructs are essential for making decisions and repeating actions in your code. In the next section, we will dive into functions and lambdas, which will further enhance your ability to write modular and reusable code.
Kotlin Programming Course
Module 1: Introduction to Kotlin
- Introduction to Kotlin
- Setting Up the Development Environment
- Kotlin Basics: Variables and Data Types
- Control Flow: Conditionals and Loops
- Functions and Lambdas
Module 2: Object-Oriented Programming in Kotlin
- Classes and Objects
- Inheritance and Interfaces
- Visibility Modifiers
- Data Classes and Sealed Classes
- Object Declarations and Companion Objects
Module 3: Advanced Kotlin Features
- Collections and Generics
- Extension Functions
- Higher-Order Functions and Functional Programming
- Coroutines and Asynchronous Programming
- DSL (Domain Specific Language) in Kotlin
Module 4: Kotlin for Android Development
- Introduction to Android Development with Kotlin
- Building User Interfaces
- Handling User Input
- Networking and Data Storage
- Testing and Debugging