Pascal Triangle in Shell Script
In shell scripting, we can write a program to generate Pascal’s Triangle using loops and conditional statements. Pascal’s Triangle is a triangular array of binomial coefficients. Each number is the sum of the two numbers directly above it.
Here is an example of a shell script that generates Pascal’s Triangle:
#!/bin/bash
# Function to calculate binomial coefficient
binomial_coefficient() {
local n=$1
local k=$2
local result=1
local i
if [[ $k -gt $n/2 ]]; then
k=$(( n - k ))
fi
for ((i=0; i<k; i++)); do
result=$(( result * (n - i) / (i + 1) ))
done
echo $result
}
# Function to generate Pascal's Triangle
pascal_triangle() {
local n=$1
local i
local j
for ((i=0; i<n; i++)); do
for ((j=0; j<=i; j++)); do
coefficient=$(binomial_coefficient $i $j)
echo -n "$coefficient "
done
echo
done
}
# Main script
read -p "Enter the number of rows: " rows
pascal_triangle $rows
In the above script, we define two functions – binomial_coefficient
and pascal_triangle
.
The binomial_coefficient
function calculates the binomial coefficient using the formula C(n,k) = n! / (k! * (n-k)!). It takes two parameters – n and k – and returns the result.
The pascal_triangle
function generates Pascal’s Triangle up to the specified number of rows. It iterates over the rows and columns using nested loops. For each element, it calls the binomial_coefficient
function to calculate the corresponding binomial coefficient. It then prints the coefficient and moves to the next element in the row.
The main script prompts the user to enter the number of rows they want in the Pascal’s Triangle. It reads the input and calls the pascal_triangle
function with the input as the parameter.
Here is an example output:
Enter the number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
The output is the Pascal’s Triangle with 5 rows. Each number represents the binomial coefficient for its position in the triangle.
Hope this explanation helps you understand how to generate Pascal’s Triangle in shell scripting using a simple example.