Exercise:
Write a C program to display Fibonacci Sequence.
1. Display using for loop
Click Here to View the Solution!
#include <stdio.h>
int main() {
int i, num, nextTerm;
int t1 = 0;
int t2 = 1;
printf("Enter the number of terms: ");
scanf("%d", &num);
printf("Fibonacci Series: ");
for (i = 1; i <= num; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Click Here to View the Output!
Enter the number of terms: 8
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13,
Click Here to View the Explanation!
- This program is used display a Fibonacci series up to n terms.
- Two
integer
variablest1
andt2
are initialized ast1 = 0
andt2 = 1
, which are the starting numbers of the series. - The program requests the user to enter the number of terms up to which the user wants the series to be and stores it in a variable
num
using thescanf()
function. - In a
for loop
, a condition is set which will continue the iterations of the loop up tonum
. - In the body of the loop, initially,
t1
andt2
will be printed. For the third term,t1
andt2
are added (t1 + t2) and the result is stored in the variablenextTerm
. - The
t2
value will then becomet1
and thenextTerm
will becomet2
. - The loop will continue for
num
number of times and will end after 8 terms of the Fibonacci series are printed. - The
return 0 statement
is used to exit the program execution.
2. Display using while loop
Click Here to View the Solution!
#include <stdio.h>
int main() {
int num;
int nextTerm = 0;
int t1 = 0;
int t2 = 1;
printf("Enter a positive number: ");
scanf("%d", &num);
// displays the first two terms which is always 0 and 1
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while (nextTerm <= num) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Click Here to View the Output!
Enter a positive number: 6
Fibonacci Series: 0, 1, 1, 2, 3, 5,
Click Here to View the Explanation!
- This program is used to display the Fibonacci series up to a specific number.
- Two integer variables
t1
andt2
are initialized ast1 = 0
andt2 = 1
. - The program requests the user to enter a positive number and stores it in a variable
num
using thescanf()
function. - The values of
t1
andt2
are printed first since0
and1
will always be the starting values of the Fibonacci series. - A sum of
t1
andt2
is then stored in an integer variablenextTerm
. - A
while loop
is then initialized with the condition(nextTerm <= num)
which will continue the loop until a term of the Fibonacci series is printed which is equal to or closest tonum
. - In the loop, the
t2
value will then becomet1
, thenextTerm
will becomet2
and thenextTerm
for the newt1
andt2
values is calculated. - The
return 0 statement
is used to exit the program execution.