0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Print Pascal Triangle with Output

Use a Bash script with nested loops and a function to calculate binomial coefficients, like pascal() { for ((i=0; i<$1; i++)); do for ((j=0; j<=i; j++)); do echo -n "$(binomial $i $j) "; done; echo; done; } where binomial calculates combinations.
📋

Examples

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

How to Think About It

To print Pascal's triangle, think of each number as a combination of row and position. Use a function to calculate combinations (n choose k) and print each row with spaces. Loop through rows and columns, calculating and printing each value.
📐

Algorithm

1
Get the number of rows as input.
2
For each row from 0 to n-1, do:
3
For each position in the row from 0 to current row number, do:
4
Calculate the binomial coefficient (n choose k).
5
Print the value followed by a space.
6
Move to the next line after each row.
💻

Code

bash
binomial() {
  local n=$1
  local k=$2
  local res=1
  for ((i=1; i<=k; i++)); do
    res=$(( res * (n - i + 1) / i ))
  done
  echo $res
}

pascal() {
  local rows=$1
  for ((i=0; i<rows; i++)); do
    for ((j=0; j<=i; j++)); do
      echo -n "$(binomial $i $j) "
    done
    echo
  done
}

pascal $1
Output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
🔍

Dry Run

Let's trace printing 3 rows of Pascal's triangle through the code

1

Start outer loop for rows

i=0: print row 0

2

Calculate binomial coefficients for row 0

j=0: binomial(0,0)=1; print '1 '

3

Move to next row

i=1: j=0 binomial(1,0)=1; j=1 binomial(1,1)=1; print '1 1 '

Row (i)Position (j)Binomial(n,k)Value Printed
00binomial(0,0)1
10binomial(1,0)1
11binomial(1,1)1
20binomial(2,0)1
21binomial(2,1)2
22binomial(2,2)1
💡

Why This Works

Step 1: Calculate binomial coefficients

The binomial function calculates combinations using a loop to multiply and divide terms, avoiding factorials for efficiency.

Step 2: Nested loops print rows

Outer loop controls rows, inner loop prints each number in the row by calling binomial with current row and position.

Step 3: Print formatting

Each number is printed with a trailing space, and after each row, a newline is printed to format the triangle shape.

🔄

Alternative Approaches

Using arrays to build rows
bash
pascal_array() {
  local rows=$1
  local -a row prev
  for ((i=0; i<rows; i++)); do
    row=()
    for ((j=0; j<=i; j++)); do
      if (( j == 0 || j == i )); then
        row[j]=1
      else
        row[j]=$(( prev[j-1] + prev[j] ))
      fi
      echo -n "${row[j]} "
    done
    echo
    prev=(${row[@]})
  done
}

pascal_array $1
This method uses arrays to build each row from the previous one, which can be faster for large rows but uses more memory.
Using bc for factorial calculation
bash
factorial() {
  echo "define f(n) { if (n <= 1) return (1); return (n * f(n-1)); } f($1)" | bc
}

binomial() {
  n=$1
  k=$2
  fn=$(factorial $n)
  fk=$(factorial $k)
  fnk=$(factorial $((n-k)))
  echo $(( fn / (fk * fnk) ))
}

pascal() {
  for ((i=0; i<$1; i++)); do
    for ((j=0; j<=i; j++)); do
      echo -n "$(binomial $i $j) "
    done
    echo
  done
}

pascal $1
This uses external bc tool for factorials, which is simpler but slower and requires bc installed.

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

Time Complexity

The script uses nested loops: outer loop runs n times, inner loop runs up to n times, so total operations are proportional to n squared.

Space Complexity

The script uses a few variables and no large data structures, so space is constant regardless of input size.

Which Approach is Fastest?

Calculating binomial coefficients directly with integer arithmetic is faster and uses less memory than factorial-based or array-based methods.

ApproachTimeSpaceBest For
Direct binomial calculationO(n^2)O(1)Small to medium rows, simple scripts
Array building rowsO(n^2)O(n)Larger rows, faster repeated access
Factorial with bcO(n^3)O(1)Simple code but slower, requires bc
💡
Use integer arithmetic in Bash to avoid floating-point errors when calculating combinations.
⚠️
Beginners often try to calculate factorials directly in Bash without handling large numbers or integer division properly.