Search Here

C Program to Display Fibonacci Sequence

 


you will learn to display the Fibonacci sequence of first n numbers (entered by the user).

To understand this example, you should have the knowledge of the following C programming topics:

  • C Programming Operators
  • C while and do...while Loop
  • C for Loop
  • C break and continue

The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21

Visit this page to learn about the Fibonacci sequence.


Fibonacci Series up to n terms

#include <stdio.h>
int main() {

  int i, n;

  // initialize first and second terms
  int t1 = 0, t2 = 1;

  // initialize the next term (3rd term)
  int nextTerm = t1 + t2;

  // get no. of terms from user
  printf("Enter the number of terms: ");
  scanf("%d", &n);

  // print the first two terms t1 and t2
  printf("Fibonacci Series: %d, %d, ", t1, t2);

  // print 3rd to nth terms
  for (i = 3; i <= n; ++i) {
    printf("%d, ", nextTerm);
    t1 = t2;
    t2 = nextTerm;
    nextTerm = t1 + t2;
  }

  return 0;
}

Output

Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 

Let us suppose n = 10. First, we have printed the first two terms of the Fibonacci sequence before using a for loop to print the next n terms.

Let us see how the for loop works:

it1t2nextTerm
3011
4112
5123
6235
7358
85813
981321
10132134

Fibonacci Sequence Up to a Certain Number

#include <stdio.h>
int main() {
  int t1 = 0, t2 = 1, nextTerm = 0, n;
  printf("Enter a positive number: ");
  scanf("%d", &n);

  // displays the first two terms which is always 0 and 1
  printf("Fibonacci Series: %d, %d, ", t1, t2);
  nextTerm = t1 + t2;

  while (nextTerm <= n) {
    printf("%d, ", nextTerm);
    t1 = t2;
    t2 = nextTerm;
    nextTerm = t1 + t2;
  }

  return 0;
}

Output

Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 

In this program, we have used a while loop to print all the Fibonacci numbers up to n.

If n is not part of the Fibonacci sequence, we print the sequence up to the number that is closest to (and lesser than) n.

Suppose n = 100. First, we print the first two terms t1 = 0 and t2 = 1.

Then the while loop prints the rest of the sequence using the nextTerm variable:

t1t2nextTermnextTerm <= n
011true. Print nextTerm.
112true. Print nextTerm.
123true. Print nextTerm.
............
345589true. Print nextTerm.
5589144false. Terminate Loop.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.