Kotlin Program to Print Star Pattern
You can print a star pattern in Kotlin using nested
for loops like this: for (i in 1..5) { for (j in 1..i) print("*") println() } which prints stars in increasing order per line.Examples
Input5
Output*
**
***
****
*****
Input3
Output*
**
***
Input1
Output*
How to Think About It
To print a star pattern, think of rows and columns. For each row number from 1 to n, print that many stars. Use one loop for rows and a nested loop for printing stars in each row.
Algorithm
1
Get the number of rows (n) as input.2
For each row from 1 to n, do the following:3
Print stars equal to the current row number.4
Move to the next line after printing stars for the row.Code
kotlin
fun main() {
val n = 5
for (i in 1..n) {
for (j in 1..i) {
print("*")
}
println()
}
}Output
*
**
***
****
*****
Dry Run
Let's trace printing 3 rows of stars through the code
1
Start outer loop with i=1
Print 1 star: *
2
Next outer loop i=2
Print 2 stars: **
3
Next outer loop i=3
Print 3 stars: ***
| Row (i) | Stars Printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration representing a row.
Step 2: Inner loop prints stars
The inner for loop runs from 1 to the current row number, printing stars on the same line.
Step 3: Move to next line
After printing stars for a row, println() moves the cursor to the next line for the next row.
Alternative Approaches
Using repeat function
kotlin
fun main() {
val n = 5
for (i in 1..n) {
repeat(i) { print("*") }
println()
}
}This uses Kotlin's <code>repeat</code> function for cleaner star printing inside the loop.
Using while loops
kotlin
fun main() {
val n = 5
var i = 1
while (i <= n) {
var j = 1
while (j <= i) {
print("*")
j++
}
println()
i++
}
}This uses <code>while</code> loops instead of <code>for</code> loops, which some beginners find easier to understand.
Complexity: O(n^2) time, O(1) space
Time Complexity
The nested loops cause the program to print stars in a triangular pattern, resulting in roughly n*(n+1)/2 operations, which is O(n^2).
Space Complexity
The program uses constant extra space, only variables for loop counters, so space complexity is O(1).
Which Approach is Fastest?
All approaches use nested loops and have similar time complexity; using repeat is cleaner but performance is similar.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clear and standard approach |
| repeat function | O(n^2) | O(1) | Cleaner syntax, Kotlin idiomatic |
| while loops | O(n^2) | O(1) | Beginners familiar with while loops |
Use nested loops where the outer loop controls rows and the inner loop controls stars per row.
Forgetting to move to the next line after printing stars causes all stars to print on the same line.