Imagine you need to print the numbers from 1 to 100.
One approach would be to write:
println(1)
println(2)
println(3)
println(4)
println(5)And continue until 100.
Clearly, this would be inefficient and difficult to maintain.
Programming languages provide loops to solve exactly this problem.
A loop allows a program to execute the same block of code repeatedly without requiring you to write the same instructions again and again.
In the previous article, we learned how Kotlin can make decisions using if, else, and when.
Now we will learn how Kotlin can repeat operations using:
forloopswhileloopsdo-whileloopsRanges
breakcontinueNested loops
Practical programs
Loops are extremely important in Android development because applications frequently need to process lists, display collections of data, repeat operations, and perform tasks until a particular condition is satisfied.
What Is a Loop?
A loop is a programming structure that repeatedly executes a block of code.
For example:
Start
↓
Check condition
↓
Execute code
↓
Repeat
↓
Condition false?
↓
StopConsider printing numbers from 1 to 5:
1
2
3
4
5Instead of writing five separate println() statements, we can use a loop.
Why Are Loops Important?
Loops are useful whenever an operation needs to be performed repeatedly.
For example:
Printing numbers
Processing a list of students
Calculating totals
Searching through data
Displaying items
Processing API results
Repeating a task
Iterating through database records
Consider a shopping application.
If a cart contains 50 products, you don't want to write separate code for every product.
Instead:
Shopping Cart
↓
Loop through products
↓
Display each productThis is one of the fundamental uses of loops.
The for Loop
The for loop is one of the most commonly used loops in Kotlin.
A basic example is:
for (i in 1..5) {
println(i)
}Output:
1
2
3
4
5Let's understand what is happening.
1..5represents a range from 1 to 5.
The loop takes each value from the range and stores it in i.
The loop therefore executes five times.
Understanding the .. Operator
The .. operator creates an inclusive range.
For example:
1..5represents:
1, 2, 3, 4, 5Similarly:
10..15represents:
10, 11, 12, 13, 14, 15Example:
for (number in 10..15) {
println(number)
}Output:
10
11
12
13
14
15Printing Numbers from 1 to 10
Let's create a simple program.
fun main() {
for (i in 1..10) {
println(i)
}
}Output:
1
2
3
4
5
6
7
8
9
10Notice how only a few lines of code are needed to print ten numbers.
This becomes even more useful when working with hundreds or thousands of values.
Printing Numbers in Reverse
What if we want:
10
9
8
7
6
5
4
3
2
1We can use downTo.
for (i in 10 downTo 1) {
println(i)
}Output:
10
9
8
7
6
5
4
3
2
1Using step
Sometimes you don't want to move through every number.
For example:
2
4
6
8
10You can use step.
for (i in 2..10 step 2) {
println(i)
}Output:
2
4
6
8
10Here:
step 2means that the value increases by 2 each time.
Odd Numbers Using step
We can also print odd numbers.
for (i in 1..10 step 2) {
println(i)
}Output:
1
3
5
7
9Looping Through a String
A for loop can also process individual characters in a string.
Example:
val name = "Kotlin"
for (character in name) {
println(character)
}Output:
K
o
t
l
i
nThis can be useful when processing text.
Looping Through a List
Loops become particularly useful when working with collections.
For example:
val fruits = listOf("Apple", "Banana", "Mango", "Orange")
for (fruit in fruits) {
println(fruit)
}Output:
Apple
Banana
Mango
OrangeThe loop processes each item in the list.
Later, this concept will be extremely important in Android development when displaying lists of information.
What Is a while Loop?
A while loop repeatedly executes code while a condition remains true.
Basic syntax:
while (condition) {
// code
}Example:
var number = 1
while (number <= 5) {
println(number)
number++
}Output:
1
2
3
4
5How Does a while Loop Work?
Let's break it down.
Initially:
number = 1Kotlin checks:
number <= 5Because it is true, the loop executes.
Then:
number++increases the value.
The process continues:
1 → 2 → 3 → 4 → 5 → 6When the value becomes 6:
6 <= 5is false.
The loop stops.
Why Is number++ Important?
Consider this:
var number = 1
while (number <= 5) {
println(number)
}This loop has a problem.
The value of number never changes.
Therefore, the condition remains true forever.
This creates an infinite loop.
Always make sure that a loop has a way to eventually reach its stopping condition.
Increment and Decrement Operators
You will frequently encounter:
++
--++ increases a value by 1.
Example:
var number = 5
number++Now:
number = 6Similarly:
var number = 5
number--results in:
number = 4These operators are especially useful with loops.
The do-while Loop
The third major loop is:
do-whileIts syntax is:
do {
// code
} while (condition)Example:
var number = 1
do {
println(number)
number++
} while (number <= 5)Output:
1
2
3
4
5while vs do-while
There is an important difference.
while
The condition is checked before the loop body executes.
while (condition) {
// code
}do-while
The loop body executes at least once, and the condition is checked afterward.
do {
// code
} while (condition)Consider:
var number = 10
while (number < 5) {
println(number)
}Nothing is printed because the condition is false from the beginning.
Now consider:
var number = 10
do {
println(number)
} while (number < 5)Output:
10The code inside the do block executes once before the condition is checked.
When Should You Use Each Loop?
There is no single loop that is best for every situation.
Use for when:
You know what collection or range you want to iterate through.
Example:
for (i in 1..10) {
println(i)
}Use while when:
You want to continue until a condition changes.
Example:
while (isRunning) {
// perform task
}Use do-while when:
The code must execute at least once.
Example:
do {
// perform task
} while (condition)The break Statement
Sometimes you want to stop a loop before it reaches its normal endpoint.
Kotlin provides:
breakExample:
for (i in 1..10) {
if (i == 6) {
break
}
println(i)
}Output:
1
2
3
4
5When i becomes 6, the break statement stops the loop.
The continue Statement
The continue statement skips the current iteration and moves to the next one.
Example:
for (i in 1..5) {
if (i == 3) {
continue
}
println(i)
}Output:
1
2
4
5When i is 3, Kotlin skips that iteration.
The loop continues with 4.
break vs continue
Remember the difference:
break
↓
Stops the loop completelywhile:
continue
↓
Skips the current iterationExample:
for (i in 1..10) {
if (i == 5) {
break
}
println(i)
}Stops completely at 5.
But:
for (i in 1..10) {
if (i == 5) {
continue
}
println(i)
}skips 5 but continues with 6, 7, 8, 9, and 10.
Nested Loops
A loop can be placed inside another loop.
This is called a nested loop.
Example:
for (i in 1..3) {
for (j in 1..3) {
println("i = $i, j = $j")
}
}Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3Nested loops are useful for working with tables, grids, matrices, and other multidimensional data.
Creating a Multiplication Table
Let's use a loop to create a multiplication table.
fun main() {
val number = 5
for (i in 1..10) {
println("$number × $i = ${number * i}")
}
}Output:
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45
5 × 10 = 50This is a simple example of how loops can eliminate repetitive code.
Calculating a Sum
Loops can also be used to calculate totals.
Example:
fun main() {
var sum = 0
for (i in 1..10) {
sum += i
}
println("Sum = $sum")
}Output:
Sum = 55The program adds:
1 + 2 + 3 + ... + 10and stores the result in sum.
Finding Even Numbers
Let's print all even numbers from 1 to 20.
fun main() {
for (i in 1..20) {
if (i % 2 == 0) {
println(i)
}
}
}Output:
2
4
6
8
10
12
14
16
18
20Here we combine two concepts:
Loop + ConditionThis combination is extremely common in programming.
Finding Odd Numbers
We can modify the same program:
fun main() {
for (i in 1..20) {
if (i % 2 != 0) {
println(i)
}
}
}Output:
1
3
5
7
9
11
13
15
17
19Counting Numbers in a List
Suppose we have:
val numbers = listOf(10, 25, 40, 15, 50)We want to count numbers greater than 20.
var count = 0
for (number in numbers) {
if (number > 20) {
count++
}
}
println("Count = $count")Output:
Count = 3The numbers greater than 20 are:
25
40
50Looping Through a List in Android
Loops become especially important when working with application data.
Imagine an Android application receives:
Apple
Banana
Mango
Orangefrom a database or API.
The application needs to process each item.
Conceptually:
Data
↓
List
↓
Loop
↓
Process each item
↓
Display resultsModern Android applications often use higher-level collection and UI tools rather than manually writing loops for every display operation, but understanding loops remains essential because the underlying programming logic still depends on iteration.
A More Practical Example: Shopping Cart
Imagine a shopping application.
The cart contains:
val prices = listOf(500, 250, 1000, 750)We want to calculate the total.
var total = 0
for (price in prices) {
total += price
}
println("Total = ₹$total")Output:
Total = ₹2500The same basic concept can be used when processing data received from a database or API.
Common Loop Mistakes
1. Creating an Infinite Loop
Incorrect:
var i = 1
while (i <= 10) {
println(i)
}The value of i never changes.
Correct:
var i = 1
while (i <= 10) {
println(i)
i++
}2. Incorrect Range
Remember that:
1..5includes 5.
So it represents:
1, 2, 3, 4, 5If you need an end-exclusive range, Kotlin also provides:
1..<5which represents:
1, 2, 3, 4This distinction is useful when working with indexes and collections.
3. Modifying the Wrong Variable
Consider:
var i = 1
while (i <= 10) {
println(i)
// Incorrect variable changed here
}Make sure the variable controlling the condition is updated appropriately.
4. Using break Unnecessarily
break is useful, but excessive use can make logic harder to understand.
Before adding break, consider whether the loop itself can be designed more clearly.
Practice Exercises
Now it's your turn.
Try solving these problems without looking at the solutions.
Exercise 1: Print Numbers
Print numbers from 1 to 100 using a for loop.
Exercise 2: Reverse Counting
Print:
100
99
98
...
1using downTo.
Exercise 3: Even Numbers
Print all even numbers between 1 and 50.
Exercise 4: Odd Numbers
Print all odd numbers between 1 and 50.
Exercise 5: Multiplication Table
Take a number and print its multiplication table from 1 to 10.
Exercise 6: Sum of Numbers
Calculate the sum of numbers from 1 to 100.
Exercise 7: Factorial
Calculate the factorial of a number using a loop.
For example:
5! = 5 × 4 × 3 × 2 × 1Therefore:
5! = 120Exercise 8: Find the Largest Number
Given a list of integers, use a loop to find the largest value.
Exercise 9: Count Positive Numbers
Given a list of integers, count how many values are positive.
Exercise 10: Search a List
Given a list and a target number, determine whether the target exists in the list.
A Quick Look at Looping Through Indexes
Sometimes you need both the index and the value.
For example:
val fruits = listOf("Apple", "Banana", "Mango")You can use:
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}Output:
0: Apple
1: Banana
2: MangoThis becomes useful when you need to know both what item you are processing and where it appears in the collection.
Why Loops Matter for Android Developers
Loops may appear to be a basic programming topic, but they are used throughout software development.
Consider an Android application displaying a list of students:
Student 1
Student 2
Student 3
Student 4
...
Student 100The application doesn't need 100 separate blocks of logic.
It can process the collection programmatically.
Similarly, an application may receive hundreds of products from an API:
API
↓
JSON Data
↓
Objects/List
↓
Process Data
↓
Display UIUnderstanding iteration is therefore essential before working with collections, databases, APIs, and real-world Android projects.
What You Learned Today
In this article, we learned:
What loops are
Why loops are useful
forloopsRanges
....<downTostepwhiledo-whileIncrement and decrement
breakcontinueNested loops
Looping through strings
Looping through lists
Practical programming examples
You now know three major looping structures in Kotlin.
for
while
do-whileWhat's Coming Next?
Our Kotlin programs can now:
Store values
↓
Make decisions
↓
Repeat operationsThere is another major programming concept we need before moving deeper into Android development:
Functions.
Instead of placing an entire program inside one large block, functions allow us to divide our code into smaller, reusable pieces.
For example:
Application
│
├── loginUser()
├── calculateTotal()
├── validateInput()
└── displayResult()In the next article, we will learn:
What functions are
Creating functions
Parameters
Arguments
Return values
Default arguments
Named arguments
Single-expression functions
Practical Kotlin functions
Understanding functions will be especially important when we begin building more structured Android applications.
Final Thoughts
Loops are one of the most powerful basic tools in programming.
They allow you to replace hundreds of repetitive statements with a few lines of well-designed code.
Comments
Post a Comment