fibonacchi series in c
Fibonacci Series in C
Here is an example of how to generate the Fibonacci series in C:
#include <stdio.h>
int main() {
int n, i, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Explanation
The program starts by including the necessary header file
stdio.h
, which provides input/output functions likeprintf
andscanf
.The
main
function is defined, which is the entry point of the program.Inside the
main
function, the following variables are declared:n
: The number of terms in the Fibonacci series.i
: A loop counter.t1
andt2
: The first two terms of the series.nextTerm
: The next term in the series.The user is prompted to enter the number of terms they want in the Fibonacci series using
printf
andscanf
.The program then prints the message "Fibonacci Series: " using
printf
.A
for
loop is used to generate the Fibonacci series. The loop runs fromi = 1
toi <= n
, incrementingi
by 1 in each iteration.Inside the loop, the current term
t1
is printed usingprintf
.The next term
nextTerm
is calculated by adding the previous two termst1
andt2
.The values of
t1
andt2
are updated for the next iteration.t1
is assigned the value oft2
, andt2
is assigned the value ofnextTerm
.After the loop finishes, the
main
function returns 0, indicating successful execution of the program.
This program generates the Fibonacci series up to the specified number of terms entered by the user. Each term is calculated by adding the previous two terms. The initial terms t1
and t2
are set to 0 and 1, respectively, and the subsequent terms are calculated using a loop.