Lesson 2

Kotlin While Loops: Embracing Repetition with Control

Introduction and Overview

Welcome to our Kotlin journey! Today's destination is While Loops. A cornerstone of Kotlin programming, While Loops are used to perform repetitive tasks until a certain condition is met. Our itinerary includes an introduction to While Loops, understanding their syntax, implementing them in Kotlin, and spotting potential pitfalls such as infinite loops. Let's get started!

Getting to Know 'While' Loops

While Loops allow us to repeat a block of code until a certain condition is fulfilled. Unlike For Loops, While Loops primarily work with boolean expressions and do not necessarily iterate over collections. It's like doing a task repeatedly until a certain condition is met, for example, eating popcorn while watching a movie until either the popcorn finishes or the movie ends.

'While' Loop Syntax

Kotlin's While Loop includes a keyword while, followed by a condition in parentheses. The block of code to be repeated is enclosed in curly braces. Let's print numbers from 1 to 5 using a While Loop:

Kotlin
1fun main() { 2 var i = 1 3 // Check if i is less than or equal to 5 4 while(i <= 5) { 5 // If true, print i and increase i by 1 6 println(i) 7 i++ 8 } 9}

The loop continues as long as i <= 5. If this condition is false, the loop stops.

Understanding 'While' Loop Flow

The variable i starts as 1. The loop condition checks if i is less than or equal to 5. If this condition is true, i's value is printed, and then i is incremented. When i becomes 6, the loop halts because the condition is not met.

Practical 'While' Loop Examples

Let's use While Loops for some common tasks:

  1. Counting Numbers: Count from 1 to 10:
Kotlin
1fun main() { 2 var counter = 1 3 while(counter <= 10) { 4 println(counter) 5 counter++ 6 } 7}
  1. Printing Even Numbers: Print even numbers between 1 and 10:
Kotlin
1fun main() { 2 var num = 2 3 while(num <= 10) { 4 println(num) 5 num += 2 6 } 7}
  1. Reverse Counting: Count from 10 to 1:
Kotlin
1fun main() { 2 var countdown = 10 3 while(countdown >= 1) { 4 println(countdown) 5 countdown-- 6 } 7}
Infinite 'While' Loops

An infinite While Loop runs indefinitely because the condition remains always true. Here is an example of an accidental infinite loop:

Kotlin
1fun main() { 2 var i = 1 3 while(i <= 5) { 4 println(i) 5 // i++ missing here, causes infinite loop. 6 } 7}

Always be mindful of loop conditions to prevent infinite loops.

Lesson Summary and Next Steps

Bravo! We've learned how to use While Loops in Kotlin and how to avoid infinite loops. In the next session, we'll put your newly acquired knowledge to the test with engaging hands-on exercises. Let's continue looping in Kotlin together!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.