Careeroza
Real World Example
Delivery Tracking and Retries
Loops are everywhere in apps: a delivery tracker steps through stages, a network call is retried a few times before showing an error, and a list screen loads results page by page. Here is the logic behind a Swiggy-style tracker and a payment retry.
Example
Stages, retries with break, and pagination with ranges:
fun main() {
val stages = listOf("Order placed", "Preparing", "Picked up", "Delivered")
for ((i, stage) in stages.withIndex()) {
val marker = if (i <= 2) "✔" else "○" // current stage = 2
println("$marker $stage")
}
val maxRetries = 3
val serverRespondsOnAttempt = 2
for (attempt in 1..maxRetries) {
if (attempt == serverRespondsOnAttempt) {
println("Attempt $attempt: payment confirmed")
break
}
println("Attempt $attempt: timeout, retrying")
}
val totalItems = 23
val pageSize = 10
for (start in 0 until totalItems step pageSize) {
val end = minOf(start + pageSize, totalItems)
println("Loading restaurants ${start + 1}-$end")
}
}Output
✔ Order placed ✔ Preparing ✔ Picked up ○ Delivered Attempt 1: timeout, retrying Attempt 2: payment confirmed Loading restaurants 1-10 Loading restaurants 11-20 Loading restaurants 21-23
Practice
Exercise: Print the 7 times table (7 x 1 = 7 ... 7 x 10 = 70) with a for loop, then print the even numbers from 20 down to 10 on one line using downTo and step.
Show answer
fun main() {
for (i in 1..10) {
println("7 x $i = ${7 * i}")
}
for (n in 20 downTo 10 step 2) print("$n ")
println()
}