C program to print Fibonacci series
C program to print Fibonacci series
Fibonacci series is a series of number in which each number is the sum of preceding two numbers.
for example:
0 1 1 2 3 5 8 13 21 …
The next number is found by adding up the two numbers before it as :
- The 2 is found by adding the two numbers before it (1+1)
- The 3 is found by adding the two numbers before it (1+2),
- And the 5 is (2+3),
- and so on!
- The sequence Fn of Fibonacci numbers is defined by the
where
or
Let us see the C program to print Fibonacci series:
/*C program to print fibonacci series till N terms.*/
#include <stdio.h>
//create a function to print Fibonacci series
void getFibonacci(int a,int b, int n)
{
int sum;
if(n>0)
{
sum=a+b;
printf("%d ",sum);
a=b;
b=sum;
getFibonacci(a,b,n-1);
}
}
int main()
{
int a,b,sum,n;
int i;
a=0; //first term
b=1; //second term
printf("Enter total number of terms: ");
scanf("%d",&n);
printf("Fibonacci series is : ");
//print a and b as first and second terms of series
printf("%d\t%d\t",a,b);
//call function with (n-2) terms
getFibonacci(a,b,n-2);
printf("\n");
return 0;
}Output:
Enter total number of terms: 5
Fibonacci series is : 0 1 1 2 3
Pingback: Program to print Fibonacci Series using Recursion