0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Print Reverse Number Pattern

Use a nested loop in Bash: for ((i=n; i>=1; i--)); do for ((j=1; j<=i; j++)); do echo -n "$j "; done; echo; done to print a reverse number pattern.
📋

Examples

Input3
Output1 2 3 1 2 1
Input5
Output1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
Input1
Output1
🧠

How to Think About It

Start from the given number and count down to 1. For each number, print all numbers from 1 up to that number on one line. Repeat this until you reach 1.
📐

Algorithm

1
Get the input number n
2
Start a loop from i = n down to 1
3
For each i, start another loop from j = 1 up to i
4
Print j followed by a space without a newline
5
After inner loop ends, print a newline
6
Repeat until i reaches 1
💻

Code

bash
read -p "Enter a number: " n
for ((i=n; i>=1; i--)); do
  for ((j=1; j<=i; j++)); do
    echo -n "$j "
  done
  echo
 done
Output
Enter a number: 5 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
🔍

Dry Run

Let's trace input 3 through the code

1

Outer loop starts with i=3

Print numbers 1 to 3: 1 2 3

2

Outer loop i=2

Print numbers 1 to 2: 1 2

3

Outer loop i=1

Print number 1: 1

iPrinted line
31 2 3
21 2
11
💡

Why This Works

Step 1: Outer loop controls lines

The outer loop for ((i=n; i>=1; i--)) counts down from the input number to 1, deciding how many numbers to print on each line.

Step 2: Inner loop prints numbers

The inner loop for ((j=1; j<=i; j++)) prints numbers from 1 up to the current line number i.

Step 3: Print newline after each line

After printing numbers for one line, echo prints a newline to move to the next line.

🔄

Alternative Approaches

Using while loops
bash
read -p "Enter a number: " n
i=$n
while [ $i -ge 1 ]; do
  j=1
  while [ $j -le $i ]; do
    echo -n "$j "
    ((j++))
  done
  echo
  ((i--))
done
Uses while loops instead of for loops; slightly longer but same logic.
Using seq command
bash
read -p "Enter a number: " n
for ((i=n; i>=1; i--)); do
  seq -s ' ' 1 $i
 done
Uses the seq command to print numbers, simpler inner loop but depends on external command.

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

Time Complexity

The nested loops run approximately n + (n-1) + ... + 1 times, which sums to O(n^2).

Space Complexity

The script uses constant extra space for counters and printing, so O(1).

Which Approach is Fastest?

Using built-in commands like seq can be faster but depends on system calls; pure loops are portable and efficient enough for small n.

ApproachTimeSpaceBest For
For loopsO(n^2)O(1)Simple, portable scripts
While loopsO(n^2)O(1)Alternative control flow
seq commandO(n^2)O(1)Simpler code, depends on external command
💡
Use nested loops where the outer loop controls lines and the inner loop prints numbers per line.
⚠️
Forgetting to print a newline after each line causes all numbers to print on one line.