C Program to Implement Fibonacci Series
This is the C Program which Implements Fibonacci series upto user defined limit n
#include<stdio.h>
int main()
{
int n; //Variable to store no of terms
int first=0; //First term initializing with zero as value
int second=1; //second term initializing with one as its value
int next; //used to store the next value of series by summing up previous terms
int i; //condition initialisor
printf("Enter the number of termsn");
scanf("%d",&n); //accepting value for variable n
printf("First %d terms of fibonacci series are :-n",n);
for (i=0;i<n;i++) //loop starts and continues till counter is equal to the no of terms
{
if (i<=1) //condition if i is <=1 then next value = 1
next=i;
else //next=sum of previous two terms
{
next = first + second;
first = second; //swapping the value of first and second
second = next; //seconf value goes to next
}
printf("%dn",next);
}
return 0;
}
While Loop Implementation:
#include<stdio.h>
main()
{
long num;
printf("Enter Number of terms n");
scanf("%ld",&num);
long i=0;
long firstterm=0;
long secterm=1;
long nexterm;
while(i<num)
{
if (i<=1)
nexterm=i;
else
nexterm=firstterm+secterm;
printf("%ld n",nexterm);
firstterm=secterm;
secterm=nexterm;
i++;
}
}
OUTPUT:
Enter the number of terms
7
First 8 terms of fibonacci series are :-
1
1
2
3
5
8
13
Recent Comments