shell script to find factorial of a number

Let's write a shell script to find the factorial of a number.




Algorithm

1. Get a number

2. Use for loop or while loop to compute the factorial by using the below formula

3. fact(n) = n * n-1 * n-2 * .. 1

4. Display the result.




Factorial of a number using while loop - Shell Script

#shell script for factorial of a number
#factorial using while loop

echo "Enter a number"
read num

fact=1

while [ $num -gt 1 ]
do
  fact=$((fact * num))  #fact = fact * num
  num=$((num - 1))      #num = num - 1
done

echo $fact

gt stands for greater than (>).




Output

Enter a number

3

6

Enter a number

4

24

Enter a number

5

120




Factorial of a number using for loop - Shell Script

#shell script for factorial of a number
#factorial using for loop

echo "Enter a number"
read num

fact=1

for((i=2;i<=num;i++))
{
  fact=$((fact * i))  #fact = fact * i
}

echo $fact



Output

Enter a number

3

6

Enter a number

4

24

Enter a number

5

120


Topics You Might Like