18.2K
Table of Contents
In this article, we’ll see Shell script to print Fibonacci series.
What is Fibonacci series?
Fibonacci series is defined as a sequence of numbers in which the first two numbers are 1 and 1, or 0 and 1, depending on the selected beginning point of the sequence, and each subsequent number is the sum of the previous two.
Algorithm
- Start
- Declare variables i, a,b , show
- Initialize the variables, a=0, b=1, and show =0
- Enter the number of terms of Fibonacci series to be printed
- Print First two terms of series
- Use loop for the following steps
-> show=a+b
-> a=b
-> b=show
-> increase value of i each time by 1
-> print the value of show - End
Shell script to print Fibonacci series
echo "How many number of terms to be generated ?"
read n
function fibonacci
{
x=0
y=1
i=2
echo "Fibonacci Series up to $n terms :"
echo "$x"
echo "$y"
# -lt stands for equal to
while [ $i -lt $n ]
do
i=`expr $i + 1 `
z=`expr $x + $y `
echo "$z"
x=$y
y=$z
done
}
r=`fibonacci $n`
echo "$r"
Output
anupmaurya@linux:~$ ./test.sh
How many number of terms to be generated ?
10
Fibonacci Series up to 10 terms :
0
1
1
2
3
5
8
13
21
34
anupmaurya@linux:~$
1 comment
Nice and easy example