The Fibonacci series is a sequence where each number is the sum of the two preceding ones, starting from 0 and 1. The first few numbers in the Fibonacci sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21,...
.
Program to print Fibonacci series:
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next;
printf(“Enter the number of terms: “);
scanf(“%d”, &n);
printf(“Fibonacci Series: “);
for(int i = 0; i < n; i++) {
if(i <= 1)
next = i; // First two numbers are 0 and 1
else {
next = first + second; // Next number is the sum of the previous two
first = second; // Update the first number
second = next; // Update the second number
}
printf(“%d “, next);
}
return 0;
}
Logic Explanation:
- Initialize the first two numbers of the Fibonacci sequence:
first = 0
,second = 1
. - Start a loop from
i = 0
ton-1
. - If
i
is less than or equal to 1, printi
(since the first two numbers are 0 and 1). - For
i > 1
, calculate the next Fibonacci number asfirst + second
. Then, update the values offirst
andsecond
for the next iteration. - The loop terminates when
n
terms are printed.
Example Output:
Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8