Write a C Program to find Fibonacci series up to n
The sequence is a Fibonacci series in C where the next number is the sum of the previous two numbers. The first two terms of the Fibonacci sequence is started from 0, 1.
What is Fibonacci SeriesIt’s a unique sequence where the next number is the sum of previous two numbers.
Where the first two terms are always 0 and 1
In mathematical terms :Fn = Fn-1 + Fn-2
Where, F0 : 0 F1 : 1
Example SeriesThe series Looks like : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 …
Method 1
Write a program to print Fibonacci series method 1 below –
#include<stdio.h>
int main()
{
int n = 10;
int a = 0, b = 1;
// printing the 0th and 1st term
printf("%d, %d",a,b);
int nextTerm;
// printing the rest of the terms here
for(int i = 2; i < n; i++){
nextTerm = a + b;
a = b;
b = nextTerm;
printf("%d, ",nextTerm);
}
return 0;
}
#include<stdio.h>
int printFib(int n){
static int a = 0, b = 1, nextTerm;
if(n > 0)
{
nextTerm = a + b;
a = b;
b = nextTerm;
printf("%d, ",nextTerm);
printFib(n-1);
}
}
int main()
{
int n = 10;
printf("0, 1, ");
// n-2 as 2 terms already printed
printFib(n-2);
return 0;
}
#include<stdio.h>
#include<math.h>
int getFibo(double phi, int n) {
for(int i = 0; i <= n; i++)
{
// setting .0 precision so all leading decimals are not printed
// else would have printed 1.000000, 1.000000, 2.000000 so on....
printf("%.0lf, ",round(pow(phi, i) / sqrt(5)));
}
}
int main ()
{
int n = 15;
double phi = (1 + sqrt(5)) / 2;
getFibo(phi, n);
return 0;
}
#include
int main(){
int n,i,a=0,b=1,c;
printf(“Enter a number: “);
scanf(“%d”,&n);
if(n<0){
printf("Number of terms should be always greater than 0\n");
}
else{
for(i=1;i<=n;i++){
printf("%d ",a);
c=a+b;
a=b;
b=c;
}
}
}
#include
int main(){
int n,i,a=0,b=1,c;
printf(“Enter a number: “);
scanf(“%d”,&n);
if(n<0){
printf("Number of terms should be always greater than 0\n");
}
else{
for(i=1;i<=n;i++){
printf("%d ",a);
c=a+b;
a=b;
b=c;
}
}
}