hi,
I'm a beginner to UNIX and got some problem in this fibonacci.Please help me out.Here is the code:
fibo()
{
if [ "$1" -gt "1" ]
then
fibo=` expr {fibo ($1 - 2)} + {fibo ($1 - 1)}` | bc
echo $fibo
fi
}
echo "enter a number:"
read x
#echo "The fibonnacci series for value $x is:"
fibo $x
And i'm getting the error as:
ksh fibo.sh
enter a number:
4
fibo.sh[4]: syntax error at line 1 : `(' unexpected
plese help me out.
Thanks in advance.
Janani
I suppose the point was to try and learn recursion in shell programming...
But why????
IMHO -- recursion is rarely necessary, and typically overly complex.
To that end, here is a non-recursive solution,
following the algorithm from: Wiki_Fibonacci_series
fibo()
{
num=$1
if [ $num -eq 0 ]; then
print 0
return
fi
if [ $num -eq 1 ]; then
print 0, 1
return
fi
print -n 0, 1
first=0
second=1
counter=2
while [ $counter -lt $num ]; do
curr_total=$(( first + second ))
print -n ", $curr_total"
first=$second
second=$curr_total
counter=$(( counter + 1 ))
done
print
return
}
echo "enter a number: "
read x
echo "The fibonnacci series for value $x is:"
fibo $x
fibo()
{
num=${1:-100}
n2=1
n1=0
while n=$(( $n1 + $n2 )); [ $n -le $num ]
do
printf "%d " "$n"
n1=$n2
n2=$n
done
echo
}
## The loop continues until the user enters a valid number
while :
do
printf "Enter a number: "
read number
case $number in
*[!0-9]* | "") printf "\a*** Invalid number ***\n" >&2 ;;
*) break ;;
esac
done
fibo "$number"