Practical-04
Write a program to display first 25 terms of Fibonacci series using recursion.
Introduction
In this program, we will learn to write a recursive function to calculate the fibonacci series of a given number.
Algorithm
- Declare a function called "fibonacci" which will compute the Fibonacci series.
- In the main function, prompt the user to enter the number of terms they want in the sequence.
- Read the number of terms entered by the user.
- Loop through the first "n" terms of the Fibonacci sequence, printing each term.
- In the loop, call the "fibonacci" function to compute each term of the sequence.
- Inside the "fibonacci" function, use recursion to calculate the Fibonacci of "n".
- If "n" is less than or equal to 1, return "n".
- Otherwise, return the sum of the recursive calls to "fibonacci(n-1)" and "fibonacci(n-2)".
- End the program.
Code
Practical-04.c
#include<stdio.h> //import library required to print on screen
//declare a function which will compute fibbonacci series
int fibonacci(int);
void main()
{
int i, num;
printf("Enter the number of terms: ");
scanf("%d", &num); // read n terms from user
//loop through first n terms of Fibonacci sequence
for (i = 0; i < num; i++)
{
printf("%d ", fibonacci(i));
}
}
// a recursive function that returns Fibonacci of n
int fibonacci(int n)
{
if (n <= 1)
return n;
else
return (fibonacci(n-1) + fibonacci(n-2)); // recursive call of the same
}
Output
Enter the number of terms: 25
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368
Explanation
The program first asks the user to enter the number of terms. Then it calls the fibonacci function to calculate the fibonacci series. The fibonacci function is a recursive function. It calls itself until the base case is reached. The base case is when the number is 0 or 1. The fibonacci function returns the fibonacci of the given number.