0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Print Numbers 1 to n

You can print numbers from 1 to n in Kotlin using a for loop like this: for (i in 1..n) { println(i) } where n is the upper limit.
📋

Examples

Input5
Output1 2 3 4 5
Input1
Output1
Input0
Output
🧠

How to Think About It

To print numbers from 1 to n, think of counting starting at 1 and going up to n one by one. Use a loop that starts at 1 and increases by 1 each time until it reaches n, printing each number as you go.
📐

Algorithm

1
Get the input number n.
2
Start a counter i at 1.
3
While i is less than or equal to n, do the following:
4
Print the current value of i.
5
Increase i by 1.
6
Stop when i becomes greater than n.
💻

Code

kotlin
fun main() {
    val n = readLine()!!.toInt()
    for (i in 1..n) {
        println(i)
    }
}
Output
1 2 3 4 5
🔍

Dry Run

Let's trace the input 5 through the code to see how numbers 1 to 5 are printed.

1

Read input

Input n = 5

2

Start loop

i starts at 1

3

Print and increment

Print 1, then i becomes 2

4

Repeat loop

Print 2, i=3; Print 3, i=4; Print 4, i=5; Print 5, i=6

5

End loop

i=6 which is greater than n=5, stop

iPrinted Number
11
22
33
44
55
💡

Why This Works

Step 1: Reading Input

The program reads the number n from the user to know how many numbers to print.

Step 2: Using a For Loop

The for loop runs from 1 to n, making it easy to count and print each number in order.

Step 3: Printing Numbers

Inside the loop, println(i) prints the current number, so all numbers from 1 to n appear on separate lines.

🔄

Alternative Approaches

While loop
kotlin
fun main() {
    val n = readLine()!!.toInt()
    var i = 1
    while (i <= n) {
        println(i)
        i++
    }
}
This uses a <code>while</code> loop instead of <code>for</code>. It is more manual but works the same.
Using recursion
kotlin
fun printNumbers(i: Int, n: Int) {
    if (i > n) return
    println(i)
    printNumbers(i + 1, n)
}

fun main() {
    val n = readLine()!!.toInt()
    printNumbers(1, n)
}
This uses recursion to print numbers, which is less common but shows a different approach.

Complexity: O(n) time, O(1) space

Time Complexity

The loop runs from 1 to n, so it executes n times, making the time complexity O(n).

Space Complexity

The program uses a fixed amount of extra space regardless of n, so space complexity is O(1).

Which Approach is Fastest?

All approaches (for loop, while loop, recursion) have similar time complexity, but the for loop is simplest and most readable.

ApproachTimeSpaceBest For
For loopO(n)O(1)Simple and readable counting
While loopO(n)O(1)Manual control of loop variable
RecursionO(n)O(n)Demonstrating recursion but uses more stack space
💡
Use the Kotlin range operator 1..n with a for loop for simple counting.
⚠️
Forgetting that the range 1..n includes both ends, so using 1 until n will miss printing n.