Given an integer N, the task is to print the first N terms of the Fibonacci series in reverse order using Recursion .
Examples:
Input: N = 5Output: 3 2 1 1 0Explanation: First five terms are – 0 1 1 2 3.
Input: N = 10Output: 34 21 13 8 5 3 2 1 1 0
Approach: The idea is to use recursion in a way that keeps calling the same function again till N is greater than 0 and keeps on adding the terms and after that starts printing the terms.
Follow the steps below to solve the problem:
Define a function fibo(int N, int a, int b) where
N is the number of terms and
a and b are the initial terms with values 0 and 1 .
If N is greater than 0, then call the function again with values N-1, b, a+b .
After the function call, print a as the answer.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void fibo(int n, int a, int b)
{
if (n > 0) {
fibo(n - 1, b, a + b);
cout << a << " ";
}
}
int main()
{
int N = 10;
fibo(N, 0, 1);
return 0;
}
Java
import java.util.*;
public class GFG
{
static void fibo(int n, int a, int b)
{
if (n > 0) {
fibo(n - 1, b, a + b);
System.out.print(a + " ");
}
}
public static void main(String args[])
{
int N = 10;
fibo(N, 0, 1);
}
}
Python3
def fibo(n, a, b):
if (n > 0):
fibo(n - 1, b, a + b)
print(a, end=" ")
if __name__ == "__main__":
N = 10
fibo(N, 0, 1)
C#
using System;
class GFG
{
static void fibo(int n, int a, int b)
{
if (n > 0) {
fibo(n - 1, b, a + b);
Console.Write(a + " ");
}
}
public static void Main()
{
int N = 10;
fibo(N, 0, 1);
}
}
Javascript
<script>
function fibo(n, a, b)
{
if (n > 0) {
fibo(n - 1, b, a + b);
document.write(a + " ");
}
}
let N = 10;
fibo(N, 0, 1);
</script>
Output
34 21 13 8 5 3 2 1 1 0
Time Complexity: O(N)Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule. Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
01 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...