09 January 2012

Shell Script To find Factorial of a Number

3 comments

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...

3 comments:

  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
  2. what if in place of $n we want to use $1 how can we use it

    ReplyDelete
  3. Yr ye to le nhi raha hai error aa raha hai 10 number line m

    ReplyDelete