Recursive Function For Fibonacci Series
Recursive Function For Fibonacci Series
long fibonacci(long n)
{
if (n == 0 || n == 1) //Base case
return n;
else
return (fibonacci(n-1) + fibonacci(n-2)); //recursive case
}
Type the following main program together with the recursive function to test it.
#include<stdio.h>
#include<conio.h>
int main()
{
long n;
getch();
return 0;
You're working with a C program that prints the Fibonacci series using a recursive function.
This is a classic programming concept, and it's very useful to understand both recursion and
how functions work.
✅ 1. What is This Program All About?
This program:
0, 1, 1, 2, 3, 5, 8, 13, ...
F(0) = 0
F(1) = 1
F(2) = F(1) + F(0) = 1
F(3) = F(2) + F(1) = 2
F(4) = F(3) + F(2) = 3
...
This means:
● If n is 0 or 1, return n
● Otherwise, call the function again with n-1 and n-2, and add them
✅ 2. How to Run This in Dev C++
🛠 Step-by-Step Instructions:
🔹 Step 1: Open Dev C++
● Click the Dev C++ shortcut
● Go to File → New → Source File
#include <stdio.h>
#include <stdlib.h>
int main() {
long n;
printf("\n");
system("pause"); // use this instead of getch()
return 0;
}
long fibonacci(long n) {
if (n == 0 || n == 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
✅ Why the changes?
● #include <conio.h> and getch() cause errors on modern compilers
● system("pause"); keeps the window open in Windows
● Use %ld for long in scanf and printf
"This program prints the first n Fibonacci numbers using a recursive function.
The function fibonacci(n) calls itself with n-1 and n-2 to calculate the value.
The base case is when n is 0 or 1 — it just returns n.
It shows how recursion works by solving a big problem in smaller parts."
✅ Summary Table
Step Action
3 Save file as .c