Tuesday, 11 June 2013

Shell Script to accept a number n from user and display summation of the following series. 1! + 2! + 3! + … + n!

Code:
echo -n "Enter the number : "
read x
i=1
sum=0
while test $i -le $x
do
        fact=1
        a=1
        while test $a -le $i
        do
                let fact=$fact*$a
                let a=$a+1
        done
        let sum=$sum+$fact
        let i=$i+1
done

let i=2
echo -n "1!"
while test $i -le $x
do
        echo -n " + $i !"
        let i=$i+1
done
echo " = $sum"

Output:
[ty2011330@localhost ~]$ sh j08.sh
Enter the number : 4
1! + 2 ! + 3 ! + 4 ! = 33

No comments:

Post a Comment