In this tutorial, we will learn how to write a C Program to display fibonacci series. The Fibonacci series is a sequence of numbers in which each number is the sum of the two previous numbers, usually starting with 0 and 1. We will see two different ways to accomplish this:
Example 1: C Program to print Fibonacci Series using loop
In this program, we are using a for loop to print fibonacci series.
#include <stdio.h>
int main() {
int n, first_term = 0, second_term = 1, next_term, i;
// Ask user to input number of terms
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("First %d terms of the Fibonacci series:\n", n);
for (i = 0; i < n; i++) {
if (i <= 1) {
next_term = i;
} else {
next_term = first_term + second_term;
first_term = second_term;
second_term = next_term;
}
printf("%d ", next_term);
}
printf("\n");
return 0;
}
Output:
Enter the number of terms: 10 First 10 terms of the Fibonacci series: 0 1 1 2 3 5 8 13 21 34
Example 2: C Program to display Fibonacci series using recursion
In this program, we are using a recursive function fibonacci_series(n). This function calls itself to determine the nth term. For example, if fibonacci_series(3) is called, it calls itself to determine 3rd term, fibonacci_series(2) + fibonacci_series(1).
Let’s see the complete code, it prompts user to enter the number of terms and then it calls the recursive function in a loop to print series upto entered term.
#include<stdio.h>
// Function to calculate the nth Fibonacci number
int fibonacci_series(int);
int main() {
int count, i;
printf("Enter number of terms:");
scanf("%d", &count);
printf("\nFibonacci series:\n");
for (i = 0; i < count; i++) {
// Print the ith Fibonacci number
printf("%d\n", fibonacci_series(i));
}
return 0;
}
// Recursive function to calculate the nth Fibonacci number
int fibonacci_series(int num) {
if (num <= 1)
return num;
else
// Calculate the nth Fibonacci number recursively
return (fibonacci_series(num - 1) + fibonacci_series(num - 2));
}
Output:
Enter number of terms: 6
Fibonacci series:
0
1
1
2
3
5
Leave a Reply