Sunday 15 May 2016

Fibonacci Sequence #1 : C program.

For understanding what actually Fibonacci sequence is go through the definition:

"The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it."

Now, our task is to make a program

program #1: 

print first n Fibonacci numbers, where n is entered by user.

How can we start?

Clearly from definition,
Tn=Tn-1+Tn-2
So:

Declare variables for first two terms say To=a=0 and T1=b=1.
Run a loop to satisfy Tn=Tn-1+Tn-2  .
We can do this by

  • Assign Tn=Tn-1+Tn-2
  • Update Tn-2
  • Update Tn-1
  • Print Tn


You can try the given algorithm to make a program else copy the the program given below:


C Program : Fibonacci Sequence 


#include > stdio.h > int main() { int a=0,b=1,c,i,n;/*Declaration of variables: a and b as first two terms, i-counter variable, n-to be entered by user*/ printf("Enter the value of n:\n"); scanf("%d",&n);/*storing value of n*/ printf("First %d elements of Fibonacci series is:\n",n); printf("%d %d",a,b);/* first two elements*/ for(i=0;i > n-2;i++)/*loop for calculating the next terms and printing them*/ { c=a+b;/*Tn=Tn-1+Tn-2 */ a=b;/*Updating Tn-1 */ b=c;/*Updating Tn-2*/ printf(" %d ",c);/*printing the Tn*/ } }

Thanking you !

4 comments :