Monday, March 17, 2014

Fibonacci Series upto n terms – Linux Shell Script

Problem Question


Write a script to print the Fibonacci series upto n terms

Explanation of Problem


Here we wish to write a Linux Shell Script that takes a command line parameter which denotes upto which term we wish to generate Fibonacci series, and generate the same.

Code



#*Fibonacci Series*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 17-03-2014
f1=0
f2=1
echo""
echo "Fibonacci sequence for n=$1 is : "
echo""
for (( i=0;i<=$1;i++ ))
 do
  echo -n "$f1 "
  fn=$((f1+f2))
  f1=$f2
  f2=$fn
 done
echo " "
echo""

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

f1=0 f2=1 -> The first two terms of the Fibonacci Series(fixed).

echo"" -> Used to print a blank line

$1 -> The first command line argument

echo -> Linux shell command used to display the string following it to the standard output terminal display.

for (( i=0;i<=$1;i++ )) -> For loop used to loop with the code that calculates and prints the next term.

echo -n "$f1 " -> The ‘-n’ option of echo command makes the output to print in the same line. Please note a single whitespace after ‘$f1’ that I have used so that the terms are well separated.

fn=$((f1+f2)) -> We declare a variable ‘fn’ and assign it the value of expression ‘(f1+f2)’

f1=$f2 f2=$fn -> f1 is given the value of f2, and f2 the value of the new term we just found. Actually in Fibonacci series, the new term is calculated as the sum of previous two terms. Thus, we need a track of previous two terms, for which we use f1 and f2.

do done -> for loop delimiters

Output(s)



No comments:

Post a Comment

Need help?