09 January 2012

Shell Script To find Factorial of a Number

1 comment

Q. How do I write Shell Script to find factorial of a number


Ans:

#!/bin/bash
fact=1
#taking input from user
echo -e "enter a number"
read n
#if enter value less than 0
if [ $n -le 0 ] ; then
echo "invalid number"
exit
fi
#factorial logic
if [ $n -gt 0 ] ; then
for((i=$n;i>=1;i--))
do
fact=`expr $fact \* $i`
done
fi
echo "The factorial of $n is $fact"


Output


shell script to find factorial of a number

Enjoy :)


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

1 comment:

  1. Best Answer.
    echo "Enter a number: "
    read num

    i=2
    res=1

    if [ $num -ge 2 ]
    then
    while [ $i -le $num ]
    do
    res=`expr $res \* $i`
    i=`expr $i + 1`
    done
    fi

    echo "Factorial of $num = $res"

    ReplyDelete