Loop Exercises
Write a C program to print Fibonacci series up to n terms using loop. How to generate Fibonacci series up to n terms using loops in C programming. Logic to print Fibonacci series in a given range in C programming.
Required knowledge
Basic C programming, If statement, For loop, While loop
What is Fibonacci series?
Fibonacci series is a series of numbers where the current number is the sum of previous two terms. For Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... , (n-1th + n-2th)
Logic to print Fibonacci series upto n terms
Step by step descriptive logic to print n Fibonacci terms.
- Input number of Fibonacci terms to print from user. Store it in a variable say terms.
- Declare and initialize three variables, I call it as Fibonacci magic initialization. a=0, b=1 and c=0.
Here c is the current term, b is the n-1th term and a is n-2th term. - Run a loop from 1 to terms, increment loop counter by 1. The loop structure should look like for(i=1; i<=term; i++). It will iterate through n terms
- Inside the loop copy the value of n-1th term to n-2th term i.e. a = b.
Next, copy the value of nth to n-1th term b = c.
Finally compute the new term by adding previous two terms i.e. c = a + b. - Print the value of current Fibonacci term i.e. c.
Program to print Fibonacci series up to n terms
/** * C program to print Fibonacci series up to n terms */ #include <stdio.h> int main() { int a, b, c, i, terms; /* Input number from user */ printf("Enter number of terms: "); scanf("%d", &terms); /* Fibonacci magic initialization */ a = 0; b = 1; c = 0; printf("Fibonacci terms: \n"); /* Iterate through n terms */ for(i=1; i<=terms; i++) { printf("%d, ", c); a = b; // Copy n-1 to n-2 b = c; // Copy current to n-1 c = a + b; // New term } return 0; }
Output
Enter number of terms: 10
Fibonacci terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Let us modify the above code to print Fibonacci series between a given range.
Program to print Fibonacci series in given range
/** * C program to print Fibonacci series in given range */ #include <stdio.h> int main() { int a, b, c, start, end; /* Input a number from user */ printf("Enter starting term: "); scanf("%d", &start); printf("Enter end term: "); scanf("%d", &end); /* Fibonacci magic initialization */ a = 0; b = 1; c = 0; printf("Fibonacci terms: \n"); /* Iterate through terms */ while(c <= end) { /* If current term is greater than start term */ if(c >= start) { printf("%d, ", c); } a = b; // Copy n-1 to n-2 b = c; // Copy current to n-1 c = a + b; // New term } return 0; }
Output
Enter starting term: 4
Enter end term: 30
Fibonacci terms:
5, 8, 13, 21,