Tuesday, 4 October 2011

Fibonacci series in C language

/* Concept: A series whose first term is 0 and second term is 1 and all next terms are the sum of two previous terms. Eg. 0  1  1  2  3  5  8  13  21  34  55  89 ..... and so on */



#include<stdio.h>
#include<conio.h>
void main()
{
int n;
long int a=0,b=1,s=0,i;
clrscr();
printf("How many numbers you want in the fabonacci series : ");
scanf("%d",&n);
printf("%ld\t\t%ld",a,b);
for(i=0;i<n-2;i++)
{
s=a+b;
printf("\t\t%ld",s);
a=b;
b=s;
}
getch();
}





/* Explanation: first a and b will be printed after that for loop will be executed the variable s is taken to store the sum of two previous terms and after that we swap the number for our desired series... */
for i=0

s=0+1=1;
now a=b => a=1 and b=s => b=1
s is printed 1
for i=1
s=a+b => 1+1 i.e. s=2
now a=b =>a=1 and b=s =>b=2
s is printed 2
for i=2
s=1+2 => s=3
now a=b =>a=2 and b=s => b=3
s is printed 5 
and so on for the increasing values of i.... 
// HAPPY PROGRAMMING....

No comments:

Post a Comment