Tech Study

Write C++ program to generate nth fibonacci term using recursion

Introduction

To find Fibonacci series using C++, you can use the following code-:

#include <iostream>

using namespace std;

int fibonacci(int n) {
if ((n == 1) || (n == 0)) {
return (n);
} else {
return (fibonacci(n - 1) + fibonacci(n - 2));
}
}

int main() {
int n, i = 0;
cout << "Input the number of terms for Fibonacci Series:";
cin >> n;
cout << "\nFibonacci Series is as follows\n";

while (i < n) {
cout << " " << fibonacci(i);
i++;
}

return 0;
}

Output:

 

 

 

This code is a C++ program that generates the Fibonacci series of a given number of terms. The Fibonacci series is a set of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.

The program first defines a function called fibonacci(int n) which takes an integer input n and returns the nth term of the Fibonacci series. The function uses recursion and a conditional statement to compute the nth term. If the input n is 0 or 1, the function returns n as the nth term of the series. Otherwise, the function returns the sum of the (n-1)th and (n-2)th terms of the series.

The main() function then initializes two variables, n and i, and prompts the user to input the number of terms they want to generate in the series. The program then uses a while loop to iterate i from 0 to n-1, and within the loop, it calls the fibonacci() function with the value of i and prints the returned value. This continues until all the terms of the series are generated and printed, and the program terminates with return 0;

TaggedWrite C program to generate nth fibonacci term using recursion

Java Final keyword

Introduction : java final keyword The final keyword present in Java programming language is generally used for restricting the user. …

Read more

C++ Memory Management: new and delete

C++ Memory Management We know that arrays store contiguous and the same type of memory blocks, so memory is allocated …

Read more