Bash Script to Print Numbers 1 to n
Use a Bash
for loop like for i in $(seq 1 $n); do echo $i; done to print numbers from 1 to n.Examples
Input1
Output1
Input5
Output1
2
3
4
5
Input0
Output
How to Think About It
To print numbers from 1 to n, think of counting starting at 1 and going up to n. Use a loop that repeats for each number in this range and print each number on its own line.
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 after reaching n.Code
bash
#!/bin/bash read -p "Enter a number n: " n for i in $(seq 1 $n) do echo $i done
Output
Enter a number n: 5
1
2
3
4
5
Dry Run
Let's trace input n=3 through the code
1
Read input
User inputs n=3
2
Start loop
Loop runs for i in 1 2 3
3
Print numbers
Print 1, then 2, then 3
| i | Output |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
Why This Works
Step 1: Input reading
The script uses read to get the number n from the user.
Step 2: Looping through numbers
The for loop with seq 1 $n generates numbers from 1 to n.
Step 3: Printing each number
Inside the loop, echo $i prints the current number on its own line.
Alternative Approaches
Using while loop
bash
#!/bin/bash read -p "Enter a number n: " n count=1 while [ $count -le $n ] do echo $count ((count++)) done
This uses a <code>while</code> loop and manual counter increment, which is more flexible but slightly longer.
Using brace expansion
bash
#!/bin/bash read -p "Enter a number n: " n for i in $(eval echo {1..$n}) do echo $i done
Brace expansion <code>{1..n}</code> does not work with variables directly, so this method uses <code>eval</code> to expand the range.
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 script uses constant extra space for variables and prints output directly, so space complexity is O(1).
Which Approach is Fastest?
Using for i in $(seq 1 $n) is simple and efficient; while loops add more lines but similar performance; brace expansion is limited with variables.
| Approach | Time | Space | Best For |
|---|---|---|---|
| for loop with seq | O(n) | O(1) | Simple and readable for variable n |
| while loop | O(n) | O(1) | More control over loop conditions |
| brace expansion | O(n) | O(1) | Fixed ranges, not variable-friendly |
Use
seq to generate number sequences easily in Bash loops.Trying to use brace expansion with variables directly like
{1..$n} which does not work.