Fibonacci series
Fibonacci Series in C
To generate the Fibonacci series in C, you can use a loop to calculate each term based on the previous two terms. Here's an example code snippet that demonstrates how to generate the 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;
} else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
return 0;
}
Let's go through each step of the code:
We include the
stdio.h
header file to use theprintf
andscanf
functions.In the
main
function, we declare the necessary variables:n
to store the number of terms in the series.first
andsecond
to store the first two terms of the series.next
to store the next term in the series.We prompt the user to enter the number of terms they want in the series using
printf
andscanf
.We start a loop that iterates
n
times to calculate and print each term of the series.Inside the loop, we use an
if
statement to handle the first two terms of the series. Ifi
is less than or equal to 1, we setnext
toi
. Otherwise, we calculatenext
by addingfirst
andsecond
, and update the values offirst
andsecond
accordingly.Finally, we print each term of the series using
printf
.
That's it! The code will generate the Fibonacci series based on the user's input.
[[SOURCE 10]]