Bash Shell Script to find Factorial of a number

In this program, you will learn how to find factorial of a number using for loop. The formula for calculating the factorial of a number is-

n! = 1 * 2 * 3 * 4 * 5 * ... * n
#Bash script to find factorial of a number
echo -n "Enter a number: "
read number
factorial=1
for(( i=1; i<=number; i++ ))
do
  factorial=$[ $factorial * $i ]
done
echo "The factorial of $number is $factorial"

Output of the above program

Enter a number: 6
The factorial of 6 is 720

Explanation of the above code-

for loop will iterate through all numbers from 1 to the entered number and stores the multiplication of each number in a factorial variable.

Recommended Posts