Ruby Program to Print Star Pattern
5.times { |i| puts '*' * (i + 1) } which prints stars increasing from 1 to 5 in each line.Examples
How to Think About It
Algorithm
Code
puts 'Enter number of lines:' lines = gets.to_i (1..lines).each do |i| puts '*' * i end
Dry Run
Let's trace the example where the input is 5 lines through the code.
Input number of lines
User inputs 5, so lines = 5
Start loop from 1 to 5
Loop variable i starts at 1
Print stars for each line
For i=1, print '*' * 1 => '*'
Next iterations
i=2 prints '**', i=3 prints '***', i=4 prints '****', i=5 prints '*****'
| i | Stars Printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
| 4 | **** |
| 5 | ***** |
Why This Works
Step 1: Loop controls lines
The loop runs from 1 to the number of lines, controlling how many lines are printed.
Step 2: Stars printed per line
For each line number i, printing '*' repeated i times creates the star pattern.
Step 3: Output formatting
Each puts prints stars and moves to the next line automatically.
Alternative Approaches
puts 'Enter number of lines:' lines = gets.to_i lines.times do |i| puts '*' * (i + 1) end
puts 'Enter number of lines:' lines = gets.to_i count = 1 while count <= lines puts '*' * count count += 1 end
Complexity: O(n^2) time, O(1) space
Time Complexity
The outer loop runs n times, and each line prints up to n stars, so total operations are proportional to n squared.
Space Complexity
No extra space is used except for loop variables and temporary strings, so space is constant.
Which Approach is Fastest?
All approaches have similar time and space complexity; using times or each is mostly a style choice.
| Approach | Time | Space | Best For |
|---|---|---|---|
| each loop | O(n^2) | O(1) | Readability and clarity |
| times loop | O(n^2) | O(1) | Concise code with zero-based index |
| while loop | O(n^2) | O(1) | Manual control, beginner-friendly |
'*' * n to print repeated stars easily.