0
0
Kotlinprogramming~3 mins

Why For loop with ranges in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could tell your program to count for you instead of writing every step yourself?

The Scenario

Imagine you want to count from 1 to 10 and print each number. Doing this by writing each number manually is like writing a list of numbers one by one on paper.

The Problem

Writing each step manually is slow and boring. If you want to count to 100 or 1000, it becomes impossible to do without mistakes or wasting a lot of time.

The Solution

Using a for loop with ranges lets you tell the computer to count for you automatically. You just say the start and end numbers, and the loop repeats the action for each number in that range.

Before vs After
Before
println(1)
println(2)
println(3)
// ... up to 10
After
for (i in 1..10) {
    println(i)
}
What It Enables

This lets you easily repeat tasks many times without writing repetitive code, saving time and avoiding errors.

Real Life Example

For example, if you want to print a list of page numbers for a book from 1 to 50, a for loop with ranges does it quickly and cleanly.

Key Takeaways

Manually repeating code is slow and error-prone.

For loops with ranges automate repetition over a sequence of numbers.

This makes your code shorter, clearer, and easier to maintain.