Loading...
C Program to Print Fibonacci Sequence

C Program to Print Fibonacci Sequence

In this example, we will learn to print the Fibonacci sequence of first n numbers (entered by the user).

Remainder :

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


What is a Fibonacci Sequence/Series?

The Fibonacci Series is a set of numbers that starts with 0 followed by 1 and after that each number is equal to the sum of the preceding two numbers.

The Fibonacci series : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.......

Fibonacci Series up to n terms

#include <stdio.h>

int main() {
  int i, num, term1 = 0, term2 = 1, nextTerm;
  printf("Enter the number of terms: ");
  scanf("%d", &num);
  printf("Fibonacci Series : ");
  for (i = 1; i <= num; i++) {
    printf("%d, ", term1);
    nextTerm = term1 + term2;
    term1 = term2;
    term2 = nextTerm;
  }
  return 0;
}

Output

Enter the number of terms: 15
Fibonacci Series : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,

Fibonacci Sequence Up to a Certain Number

#include <stdio.h>

int main() {
  int num, term1 = 0, term2 = 1, nextTerm = 0;
  printf("Enter a number : ");
  scanf("%d", &num);
  printf("Fibonacci Series : %d, %d, ", term1, term2);
  nextTerm = term1 + term2;
  while (nextTerm <= num) {
    printf("%d, ", nextTerm);
    term1 = term2;
    term2 = nextTerm;
    nextTerm = term1 + term2;
  }
  return 0;
}

Output

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

- Related Topics