Hello every body. I am trying to find the factorial using the following code. But it is giving the syntax error. I tried very much but in vain. Thanks in advance for helping me
factorial()
{
if [ $1 -gt 1 ]
then
y=`expr $1 - 1`
x=$(( $1 \* factorial $y ))
return $x
else
return 1
fi
}
echo -n "Enter number = "; read n
factorial $n
Hello every body. I am trying to find the factorial using the following code. But it is giving the syntax error. I tried very much but in vain. Thanks in advance for helping me
factorial()
{
if [ $1 -gt 1 ]
then
y=`expr $1 - 1`
x=$(( $1 \* factorial $y ))
return $x
else
return 1
fi
}
echo -n "Enter number = "; read n
factorial $n
HI,
I have made a small change in your code and it is working fine for me...try it...
factorial()
{
if [ $1 -gt 1 ]
then
y=`expr $1 - 1`
factorial $y
#x=$(( $1 \* factorial $y )) -- I have commented this
x=$(( $1 * $? ))
return $x
else
return 1
fi
}
echo -n "Enter number = "; read n
factorial $n
echo $?
As far as i know, recursive functions are not supported in Shell Scripting.
Anyways, the following script will help you to get the factorial of a number.
#! /bin/sh
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
Please review our rules and note:
(4) Do not 'bump up' questions if they are not answered promptly. No duplicate or cross-posting and do not report a post or send a private message where your goal is to get an answer more quickly.
I have merged your two different threads. Please do not do this again.