Welcome to The Coding College! In this tutorial, we will explore the while loop in Kotlin, a fundamental control structure for repetitive tasks in programming. By mastering loops, you can simplify your code and reduce redundancy.
What is a While Loop?
A while loop in Kotlin repeatedly executes a block of code as long as the given condition evaluates to true
. It is commonly used when the number of iterations is unknown and depends on a condition being met.
Basic Syntax:
while (condition) {
// Code to execute
}
How While Loops Work
- The condition is evaluated before each iteration.
- If the condition is
true
, the code block inside the loop is executed. - This process continues until the condition becomes
false
.
Example of a While Loop
Let’s look at a simple example to print numbers from 1 to 5:
fun main() {
var number = 1
while (number <= 5) {
println(number)
number++
}
}
Output:
1
2
3
4
5
Kotlin Infinite While Loop
A while loop without a condition that eventually becomes false
can result in an infinite loop. Be cautious and ensure that the condition is properly managed.
Example:
fun main() {
var count = 1
while (true) {
println("Count: $count")
count++
if (count > 5) break // Exit the loop
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Kotlin While with User Input
You can use a while loop to process user input dynamically:
Example:
fun main() {
var input: String
do {
println("Enter a word (type 'stop' to exit):")
input = readLine() ?: ""
} while (input != "stop")
println("Program exited.")
}
The Do…While Loop
Kotlin also provides a do…while loop, which ensures that the code block runs at least once, even if the condition is false
.
Syntax:
do {
// Code to execute
} while (condition)
Example:
fun main() {
var number = 1
do {
println(number)
number++
} while (number <= 5)
}
Output:
1
2
3
4
5
Comparison: While vs Do…While
Aspect | While Loop | Do…While Loop |
---|---|---|
Condition Check | Before the code block executes | After the code block executes |
Execution Count | May not execute if the condition is false | Executes at least once, even if the condition is false |
Practical Example: Factorial Using While Loop
Here’s an example of calculating the factorial of a number using a while loop:
fun main() {
val num = 5
var factorial = 1
var i = 1
while (i <= num) {
factorial *= i
i++
}
println("Factorial of $num is $factorial")
}
Output:
Factorial of 5 is 120
Best Practices for While Loops
- Avoid Infinite Loops: Ensure the condition will eventually become
false
. - Update Loop Variables: Modify variables inside the loop to prevent endless execution.
- Use Break Statements Wisely: Exit loops only when necessary and clearly indicate the reason.
Learn More on The Coding College
The while loop is a key component of any programming language. With its versatility, you can handle various repetitive tasks effectively. Visit The Coding College for more Kotlin tutorials, coding tips, and advanced programming concepts.
Conclusion
The while loop is an essential tool in Kotlin for controlling program flow. By understanding how to use while and do…while loops, you can write efficient, reusable code for a variety of tasks.