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.
create a C program that generates Fibonacci series upto a specified number N.
Write a shell script to print the n terms in a Fibonacci Series
Create a program that generates and prints the Fibonacci series up to a specified number 'N'. The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding numbers, starting with 0 and 1. Your program should take an integer input 'N' and display the Fibonacci series up to the Nth term using a while loop.Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... Note: This question is one of the most asked questions in placements.Input format :The input consists of a positive integer N.Output format :The output displays the Fibonacci series up to the Nth term separated by space.
A Fibonacci sequence is a sequence of numbers (called Fibonacci numbers) in which each number is the sum of the two preceding ones as following: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... The task is to implement two functions in C a) using recursive function style, F(n) = F(n − 1) + F(n − 2) when n ≥ 2, F(0) = 0, F(1) = 1.
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.