0
0
RubyProgramBeginner · 2 min read

Ruby Program to Print Numbers 1 to n

In Ruby, you can print numbers from 1 to n using a loop like for i in 1..n do puts i end where n is the limit.
📋

Examples

Input3
Output1 2 3
Input1
Output1
Input0
Output
🧠

How to Think About It

To print numbers from 1 to n, start from 1 and keep increasing by 1 until you reach n. For each number, print it on a new line. If n is zero or less, print nothing.
📐

Algorithm

1
Get the input number n
2
Start a loop from 1 to n
3
For each number in the loop, print the number
4
End the loop
💻

Code

ruby
puts "Enter a number:"
n = gets.to_i
for i in 1..n do
  puts i
end
Output
Enter a number: 1 2 3
🔍

Dry Run

Let's trace input 3 through the code

1

Input n

User enters 3, so n = 3

2

Start loop

Loop from i = 1 to 3

3

Print i

Print 1

4

Next iteration

i = 2, print 2

5

Next iteration

i = 3, print 3

6

End loop

Loop ends after i = 3

i
1
2
3
💡

Why This Works

Step 1: Getting input

We use gets.to_i to read the number n from the user and convert it to an integer.

Step 2: Looping through numbers

The for i in 1..n loop runs from 1 to n, including both ends.

Step 3: Printing each number

Inside the loop, puts i prints the current number on a new line.

🔄

Alternative Approaches

Using while loop
ruby
puts "Enter a number:"
n = gets.to_i
i = 1
while i <= n
  puts i
  i += 1
end
This uses a while loop instead of for; it is more flexible but slightly longer.
Using upto method
ruby
puts "Enter a number:"
n = gets.to_i
1.upto(n) { |i| puts i }
This is a Ruby-specific method that is concise and readable.

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

Time Complexity

The loop runs n times, printing each number once, so time grows linearly with n.

Space Complexity

Only a few variables are used, so space is constant regardless of n.

Which Approach is Fastest?

All approaches run in O(n) time; using upto is most idiomatic and concise in Ruby.

ApproachTimeSpaceBest For
for loopO(n)O(1)Simple and clear for beginners
while loopO(n)O(1)More control over loop conditions
upto methodO(n)O(1)Concise and idiomatic Ruby code
💡
Use Ruby's upto method for a clean and simple way to print numbers from 1 to n.
⚠️
Forgetting to convert input to integer with to_i causes errors or no output.