Write a C Program to Print 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. This series has fascinated mathematicians and computer scientists for years due to its applications in various fields, including mathematics, biology, and computer science. In this article, we will explore how to write a simple C program to print the Fibonacci series.
Understanding the Fibonacci Series
Before we dive into writing the program, let's understand the Fibonacci series:
- The first two numbers in the Fibonacci series are usually defined as 0 and 1.
- The third number is the sum of the first two: 0 + 1 = 1.
- The fourth number is the sum of the second and third: 1 + 1 = 2.
- This process continues indefinitely, with each number being the sum of the two preceding ones.
The Fibonacci series starts like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Here's a C Program to Print Fibonacci Series:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, first = 0, second = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series:\n");
for (i = 0; i < n; i++)
{
if (i <= 1)
next = i;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
}
Code Explanation
- In the main function, we declare variables n and i. n will store the number of terms the user wants in the Fibonacci series, and i is a loop counter.
- We initialize first and second to 0 and 1, respectively, which are the first two numbers in the Fibonacci series. We also declare a variable next to store the next number in the series.
- We prompt the user to enter the number of terms they want in the series.
- We use a for loop to generate and print the Fibonacci series up to n terms. If i is less than or equal to 1, we set next to the value of i. Otherwise, we calculate next by adding first and second, update first and second to the last two numbers in the series, and print next.
- The loop continues until we have printed the desired number of terms.
Output: