0
0
RubyProgramBeginner · 2 min read

Ruby Program to Print Star Pattern

You can print a star pattern in Ruby using nested loops like 5.times { |i| puts '*' * (i + 1) } which prints stars increasing from 1 to 5 in each line.
📋

Examples

Input5
Output* ** *** **** *****
Input3
Output* ** ***
Input1
Output*
🧠

How to Think About It

To print a star pattern, think of each line as having a number of stars equal to the line number. Start from line 1 with one star, then line 2 with two stars, and so on until the given number of lines. Use a loop to repeat this printing for each line.
📐

Algorithm

1
Get the number of lines to print from the user or set a fixed number.
2
Start a loop from 1 to the number of lines.
3
For each iteration, print stars equal to the current line number.
4
Move to the next line and repeat until all lines are printed.
💻

Code

ruby
puts 'Enter number of lines:'
lines = gets.to_i

(1..lines).each do |i|
  puts '*' * i
end
Output
* ** *** **** *****
🔍

Dry Run

Let's trace the example where the input is 5 lines through the code.

1

Input number of lines

User inputs 5, so lines = 5

2

Start loop from 1 to 5

Loop variable i starts at 1

3

Print stars for each line

For i=1, print '*' * 1 => '*'

4

Next iterations

i=2 prints '**', i=3 prints '***', i=4 prints '****', i=5 prints '*****'

iStars 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

Using times loop
ruby
puts 'Enter number of lines:'
lines = gets.to_i

lines.times do |i|
  puts '*' * (i + 1)
end
This uses zero-based index from times, so add 1 to get correct star count.
Using while loop
ruby
puts 'Enter number of lines:'
lines = gets.to_i
count = 1
while count <= lines
  puts '*' * count
  count += 1
end
While loop is more manual but works the same way.

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.

ApproachTimeSpaceBest For
each loopO(n^2)O(1)Readability and clarity
times loopO(n^2)O(1)Concise code with zero-based index
while loopO(n^2)O(1)Manual control, beginner-friendly
💡
Use string multiplication like '*' * n to print repeated stars easily.
⚠️
Beginners often forget to add 1 to the loop index when using zero-based loops, resulting in no stars printed on the first line.