Fibonacci numbers

Script to display Fibonacci series.

In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence:
0,\;1,\;1,\;2,\;3,\;5,\;8,\;13,\;21,\;34,\;55,\;89,\;144,\; \ldots\; (sequence A000045 in OEIS).
By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
F_n = F_{n-1} + F_{n-2},\!\,
with seed values
F_0 = 0,\; F_1 = 1.

                                           -Wikipedia http://en.wikipedia.org/wiki/Fibonacci_number )



note: If you want only 5 rows of Fibonacci series , this for loop will do
--------------------------------------------------------
for (( i=0; i<5; i++ ));do
echo $((11**$i))
done
--------------------------------------------------------


-------------------------------------------------------------------------------------------------------------------------------------------------
HOW THIS SCRIPT WORKS:
Proper commends are provided in the script itself to make it understandable.
'tput' is command line tool to change the postion of the prompt.
-------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
#!/bin/bash

#for displaying fibonacci numbers

num=1
zero[1]=1
zero[2]=1

read -p "Please enter number of rows:"
#for exiting script if 0 or no number is entered
if [[ $REPLY == 0 || $REPLY == $null ]];then
exit 0
fi

tput cuf $(($(tput cols)/2))
echo "1"
for (( i=1; i<$REPLY; i++ ));do
   
    for (( k=1; k<=$i; k++ ));do
#for getting each number for addition and assigning to array 'a'         
         a[$k]=$(echo "$num%(10^${zero[$k]})" | bc)
         num=$(echo "$num/(10^${zero[$k]})" | bc)
    done

#adding adjascent numbers assigned to array 'a'   
    for (( j=0; j<=$i; j++ ));do
        l=$((j+1))
        sum=$((a[j]+a[l]))
        wordcont=$(echo $sum | wc -c)
        zero[l]=$((wordcont-1))
        totalsum="$totalsum $sum"
    done
    num=$(echo $totalsum | sed 's/ //g')

#finding position of terminal prompt and printing value
    length=$(echo $totalsum | wc -c)
    postion=$((($(tput cols)-$length)/2))
    tput cuf $postion 2>/dev/null
    echo "$totalsum"
    totalsum=$null
done


-------------------------------------------------------------------------------------------


In my system the script is named fibonacci. If you want ,say 15 rows , of fibanocci series ; type fibonacci and press Enter . When script ask you for number of rows to be displayed , enter 15 and press Enter  and ...




.. Howzzat ?? 



Enjoy Linux !!

Dont know what to do with these codes ?? click here

No comments:

Post a Comment