Problem statement
Write a program to take a number from user as an limit of a series and print Fibonacci series upto given input.
What is meant by Fibonacci series or sequence?
The Fibonacci sequence is a series where the next term is the sum of previous two terms. The first two terms of the Fibonaccii sequence is 0 followed by 1.
For example:
1 |
0 1 1 2 3 5 8.... |
Here first two numbers 0 and 1 are same. Then 3rd term is an addition of 2nd and 1st term i.e. 0+1 = 1.
Then 4th term is an addition of 3rd and 2nd term i.e. 1+2 = 3. In this way, next term is sum of previous terms and we get Fibonacci series.
Program to find Fibonacci series up to given number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<stdio.h> #include<string.h> int main() { int a=0, b=1, c=0, num, i=0; printf("Enter a number up to you want a series\n"); scanf("%d", &num); printf("following is a fibonacci sequence\n"); while(1) { c = a + b; if(c > num) { break; } printf("%d\t", c); a = b; b = c; } } |
Output:
1 2 3 4 |
Enter a number up to you want a series 15 following is a fibonacci sequence 1 2 3 5 8 13 |
Fibonacci Series up to N number of terms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <stdio.h> int main() { int i, n, t1 = 0, t2 = 1, nextTerm; printf("Enter the number of terms:\n "); scanf("%d", &n); printf("First %d terms of Fibonacci Series are: \n ",n); for (i=1; i<=n; ++i) { printf("%d ", t1); nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; } return 0; } |
Output
1 2 3 |
Enter the number of terms: 6 First 6 terms of Fibonacci Series are: 0 1 1 2 3 5 |