Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program to Print Fibonacci Series

$
0
0

Fibonacci series is a series of numbers where each number is the summation of two previous numbers. The first two numbers of Fibonacci series are 0 and 1. Here is an example of Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377.

Loop Version

void print_fibonacci_series(int n) {
  int i = 0;
  int n1 = 0, n2 = 1, next;
  
  if (n < 1 ) return;
  
  if (n > 0) printf("0 ");
  if (n > 1) printf("1 ");
  
  for (i = 2; i < n; i++) {
    next = n1 + n2;
    printf("%d ", next);
    n1 = n2;
    n2 = next;
  }
}

The function, print_fibonacci_series(), prints a Fibonacci series of n numbers.

Recursive Version

int fibonacci(int n) {
  if (n < 2) return n;
  return fibonacci(n-1) + fibonacci(n-2);
}

void print_fibonacci_series(int n) {
  int i = 0;
  
  for (i = 0; i < n; i++) {
    printf("%d ", fibonacci(i));
  }
}

This version looks very simple but very inefficient. Number of add operations increases exponentially with the increase of number of elements in the series. For example, if you want to print 10 numbers, first version will have 10 (8 to be precise) add operations but this recursive version will have 133 add operations. If you want to print 20 numbers, first version will have 20 (18 to be precise) but the recursive version will have 17690 add operations. Now if you increase the number to 30, first version will have 30 add operations but second version will have 2178278 add operations. If you see how inefficient this version is. You need to be very careful about using it for bigger Fibonacci series.

The Complete Program

Here is the complete program that you can compile and run.

#include <stdio.h>

void print_fibonacci_series(int n) {
  int i = 0;
  int n1 = 0, n2 = 1, next;
  
  if (n < 1 ) return;
  
  if (n > 0) printf("0 ");
  if (n > 1) printf("1 ");
  
  for (i = 2; i < n; i++) {
    next = n1 + n2;
    printf("%d ", next);
    n1 = n2;
    n2 = next;
  }
}

int main(){
  int n = 0;
  
  printf("How many Fibonacci numbers?: ");
  scanf("%d", &n);

  printf("Fibonacci series:\n");
  print_fibonacci_series(n);
  return 0;
}

Output of the program:

How many Fibonacci numbers?: 15
Fibonacci series:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

The post C Program to Print Fibonacci Series appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>