Write a C program to print the Fibonacci series using recursion and without using recursion.
Question
Write a C program to print the Fibonacci series using recursion and without using recursion.
Solution
Sure, here are the C programs to print the Fibonacci series using recursion and without using recursion.
- Fibonacci series using recursion:
#include<stdio.h>
void printFibonacci(int n){
static int n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n-2); //n-2 because 2 numbers are already printed
return 0;
}
- Fibonacci series without using recursion:
#include<stdio.h>
int main(){
int n, n1 = 0, n2 = 1, n3, i;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",n1,n2); //printing 0 and 1
for(i=2;i<n;++i) //loop starts from 2 because 0 and 1 are already printed
{
n3 = n1 + n2;
printf("%d ",n3);
n1 = n2;
n2 = n3;
}
return 0;
}
In both programs, the user is asked to enter the number of elements to be printed in the Fibonacci series. The first two numbers of the Fibonacci series are always 0 and 1. The next number is found by adding up the two numbers before it.
Similar Questions
create a C program to print Fibonacci series upto a specified number N using while loop.
Generate the Fibonacci sequence up to the 10th term and calculate the value of the 10th term.
Plot the Fibonacci numbers from n = 1 to 14, together with F(n) = n^2 use clion by c codes
What correction should be made to the following code to calculate the Fibonacci number correctly?def fib(n): return fib(n-1) + fib(n-2)
write a program to print integer no, from 1 to n where n is the input from the user using do while loop in c language use getch
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.