Write a program to find the nth term in the Fibonacci series using recursion. Note that the first 2 terms in the Fibonacci Series are 0 and 1.
INPUT & OUTPUT FORMAT:
Input consists of an integer.
Refer sample input and output for formatting specifications.
All text in bold corresponds to the input and the rest corresponds to output.
SAMPLE INPUT & OUTPUT:
5
The term 5 in the fibonacci series is 3
Answers
Answer:
/*
* C Program to find the nth number in Fibonacci series using recursion
*/
#include <stdio.h>
int fibo(int);
int main()
{
int num;
int result;
printf("Enter the nth number in fibonacci series: ");
scanf("%d", &num);
if (num < 0)
{
printf("Fibonacci of negative number is not possible.\n");
}
else
{
result = fibo(num);
printf("The %d number in fibonacci series is %d\n", num, result);
}
return 0;
}
int fibo(int num)
{
if (num == 0)
{
return 0;
}
else if (num == 1)
{
return 1;
}
else
{
return(fibo(num - 1) + fibo(num - 2));
}
}
Explanation:
hope it helps u my frd
#Keep smiling :)
Answer:
Recursive Fibonacci Series in C++
#include <iostream>
using namespace std;
int fib(int x) {
if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2));
}
}
int main() {
int x , i=0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
cout << " " << fib(i);
i++;
}
return 0;
}
Recursive Fibonacci in Python
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print(fibonacci(i))
Program Logic:
- Take the number of terms from the user and store it in a variable.
- Pass the number as an argument to a recursive function.
- Define the base condition as the number to be lesser than or equal to 1.
- Otherwise call the function recursively with the argument as the number minus 1 added to the function called recursively with the argument as the number minus 2.
- Use a for loop and print the returned value which is the Fibonacci series.
#SPJ2