Kotlin Program to Print Numbers 1 to n
for loop like this: for (i in 1..n) { println(i) } where n is the upper limit.Examples
How to Think About It
Algorithm
Code
fun main() {
val n = readLine()!!.toInt()
for (i in 1..n) {
println(i)
}
}Dry Run
Let's trace the input 5 through the code to see how numbers 1 to 5 are printed.
Read input
Input n = 5
Start loop
i starts at 1
Print and increment
Print 1, then i becomes 2
Repeat loop
Print 2, i=3; Print 3, i=4; Print 4, i=5; Print 5, i=6
End loop
i=6 which is greater than n=5, stop
| i | Printed Number |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
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
fun main() {
val n = readLine()!!.toInt()
var i = 1
while (i <= n) {
println(i)
i++
}
}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)
}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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop | O(n) | O(1) | Simple and readable counting |
| While loop | O(n) | O(1) | Manual control of loop variable |
| Recursion | O(n) | O(n) | Demonstrating recursion but uses more stack space |
1..n with a for loop for simple counting.1..n includes both ends, so using 1 until n will miss printing n.