Bash Script to Print Pascal Triangle with Output
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
How to Think About It
Algorithm
Code
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 $1Dry Run
Let's trace printing 3 rows of Pascal's triangle through the code
Start outer loop for rows
i=0: print row 0
Calculate binomial coefficients for row 0
j=0: binomial(0,0)=1; print '1 '
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 |
|---|---|---|---|
| 0 | 0 | binomial(0,0) | 1 |
| 1 | 0 | binomial(1,0) | 1 |
| 1 | 1 | binomial(1,1) | 1 |
| 2 | 0 | binomial(2,0) | 1 |
| 2 | 1 | binomial(2,1) | 2 |
| 2 | 2 | binomial(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
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 $1factorial() {
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 $1Complexity: 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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct binomial calculation | O(n^2) | O(1) | Small to medium rows, simple scripts |
| Array building rows | O(n^2) | O(n) | Larger rows, faster repeated access |
| Factorial with bc | O(n^3) | O(1) | Simple code but slower, requires bc |