Wednesday, October 12, 2016

How to generate fabonacci series in UNIX shell scripting

It has been a long time, since I last posted a blog. It feels to be in pre-school again, since I made up my mind to write something again.
Well, unlike pre-school, we all have had the privilege to study and write the code to print the famous - "Fabonacci Series" in different scripting languages and technologies.

By definition in mathematics, the Fibonacci Numbers are the numbers in the below sequence: 0,1,1,2,3,5,8,13,21,34,55,89,144, ...... and so on...

The first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.

Thus, in mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation -
Fn = Fn-1 + Fn-2
With seed values F0 = 0 and F1 = 1.

Let us see today, how to to write and interactive program in UNIX shell script -



#!/bin/bash#!/bin/bash
#####################################################
# SCRIPT:  fabonacci.bash
# USAGE:   fabonacci.bash [Number]
# PURPOSE: Generate Fibonacci sequence till the number of iterations entered by user.
# AUTHOR:  Shashank Rawlani
#####################################################

# Test the number of arguements recieved by the script

if [ $# -eq 1 ]
then
    Num=$1
else
    echo -n "Enter the number of iterations needed :"
    read Num
fi

a=0
b=1

echo "The Fibonacci sequence for the number $Num is : "

for (( i=0;i<=Num;i++ ))
do
     echo -n "$a "
     c=$((a+b))
     a=$b
     b=$c
done


echo ""




You can also find the script on www.rawlani.com.
I will be publishing a few such UNIX scripts and a few generic scripts that I use in my daily life to help me quickly do certain tasks.

Do let me know your comments below or write me on shashank@rawlani.com.

0 comments:

Post a Comment