0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Print Number Triangle Pattern

Use nested for loops in Bash: for i in {1..n}; do for j in {1..i}; do echo -n "$j "; done; echo; done to print a number triangle pattern.
📋

Examples

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

How to Think About It

To print a number triangle, think of rows increasing from 1 to n. For each row, print numbers starting from 1 up to the row number. Use two loops: the outer loop for rows and the inner loop for numbers in each row.
📐

Algorithm

1
Get input number n for the triangle height.
2
For each number i from 1 to n, do:
3
For each number j from 1 to i, print j followed by a space.
4
After inner loop ends, print a newline to start next row.
💻

Code

bash
#!/bin/bash
read -p "Enter the number of rows: " n
for ((i=1; i<=n; i++))
do
  for ((j=1; j<=i; j++))
  do
    echo -n "$j "
  done
  echo
 done
Output
Enter the number of rows: 4 1 1 2 1 2 3 1 2 3 4
🔍

Dry Run

Let's trace input 3 through the code

1

Outer loop i=1

Inner loop j runs from 1 to 1, prints '1 '

2

Outer loop i=2

Inner loop j runs from 1 to 2, prints '1 2 '

3

Outer loop i=3

Inner loop j runs from 1 to 3, prints '1 2 3 '

ijOutput
111
211
222
311
322
333
💡

Why This Works

Step 1: Outer loop controls rows

The outer for loop runs from 1 to n, each iteration prints one row.

Step 2: Inner loop prints numbers

The inner for loop prints numbers from 1 up to the current row number.

Step 3: Print newline after each row

After printing numbers in a row, echo prints a newline to start the next row.

🔄

Alternative Approaches

Using seq command
bash
#!/bin/bash
read -p "Enter rows: " n
for i in $(seq 1 $n)
do
  seq -s ' ' 1 $i
 done
Uses external command <code>seq</code> for simpler inner loop but less portable on some systems.
Using while loops
bash
#!/bin/bash
read -p "Enter rows: " n
i=1
while [ $i -le $n ]
do
  j=1
  while [ $j -le $i ]
  do
    echo -n "$j "
    ((j++))
  done
  echo
  ((i++))
done
Uses <code>while</code> loops instead of <code>for</code>, useful for beginners learning different loop types.

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

Time Complexity

The nested loops run i times for each row i from 1 to n, totaling about n*(n+1)/2 operations, which is O(n^2).

Space Complexity

The script uses constant extra space, only loop counters and no additional data structures, so O(1).

Which Approach is Fastest?

All approaches have similar O(n^2) time; using seq may be slower due to external calls but simpler code.

ApproachTimeSpaceBest For
Nested for loopsO(n^2)O(1)Standard Bash, portable
seq commandO(n^2)O(1)Simpler code, less portable
While loopsO(n^2)O(1)Beginners learning loops
💡
Use echo -n to print on the same line without newline in Bash.
⚠️
Forgetting to print a newline after each row causes all numbers to print on one line.