C PROGRAM
Find the Nth fibonacci number using recursion |C Program|
Introduction
The Fibonacci sequence is a classic mathematical concept that demonstrates the power of recursion in programming. This C program calculates the nth number in the Fibonacci series using a recursive approach. The blog post will delve into the Fibonacci series, explain the recursive solution, and provide a step-by-step breakdown of the code.
Fibonacci Series
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
Code
#include<stdio.h>
#include<conio.h>
int fib(int num);
void main() {
int num, result;
printf("Enter the nth number in Fibonacci series: ");
scanf("%d", &num);
if (num < 0) {
printf("Negative number is not possible.\n");
} else {
result = fib(num);
printf("The %dth number in Fibonacci series is %d.\n", num, result);
}
getch();
}
int fib(int num) {
if (num == 0) {
return 0;
}
if (num == 1) {
return 1;
} else {
return (fib(num - 1) + fib(num - 2));
}
}
Output
Enter the nth number in Fibonacci series: 8
The 8th number in Fibonacci series is 21.
In this example, the user inputs the value of n as 8. The program then calculates and prints the 8th number in the Fibonacci series, which is 21.
You can try running the program with different values of n to observe how it correctly calculates the corresponding Fibonacci numbers. The output will display the nth number in the Fibonacci series based on user input.
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h> and the console input/output header <conio.h>.
2. Main Function:
The main function serves as the entry point of the program.
3. Input:
Users input the value of n to find the nth number in the Fibonacci series.
4. Fibonacci Function (fib):
The fib function is a recursive function that calculates the nth Fibonacci number.
It checks for base cases where num is 0 or 1 and returns 0 or 1 accordingly.
For other cases, it recursively calls itself with fib(num - 1) + fib(num - 2).
5. Output:
The program outputs the nth number in the Fibonacci series.
Conclusion
This C program provides a practical example of calculating the nth number in the Fibonacci series using recursion. Understanding recursion and its application in the Fibonacci series is crucial for building strong programming skills.
Feel free to run the program with different values of n to observe how it correctly calculates the corresponding Fibonacci numbers. This example serves as a valuable introduction to recursive solutions in C. Happy coding!
Post a Comment
0 Comments