×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to print fibonacci series using recursion

Fibonacii series: Is a series of number in which each number is the sum of preceding two numbers.

0 1 1 2 3 5 8 ...

Problem statement

Read value of N (N for number of terms) and then print fibonacci series till N terms using recursion.

Algorithm to print fibonacci series using recursion

Base Case:

  • If n is 0, return 0.
  • If n is 1, return 1.

Recursive Case:

  • Otherwise, return the sum of the two preceding Fibonacci numbers: fibonacci(n-1) + fibonacci(n-2).

Pseudocode

function funFibonacci(n):
    if n == 0:
        return 0
    else if n == 1:
        return 1
    else:
        return funFibonacci(n - 1) + funFibonacci(n - 2)

function fibonacciSeries(n):
    for i from 0 to n-1 do:
        print(funFibonacci(i))

C program to print fibonacci series using recursion

/*C program to print fibonacii series 
till N terms.*/

#include <stdio.h>

// function to print fibonacii series
void getFibonacii(int a, int b, int n) {
  int sum;
  
  if (n > 0) {
    sum = a + b;
    printf("%d ", sum);
    a = b;
    b = sum;
    getFibonacii(a, b, n - 1);
  }
}

int main() {
  int a, b, sum, n;
  int i;

  a = 0;  // first term
  b = 1;  // second term

  printf("Enter total number of terms: ");
  scanf("%d", &n);

  printf("Fibonacii series is : ");
  // print a and b as first and second terms of series
  printf("%d\t%d\t", a, b);
  // call function with (n-2) terms
  getFibonacii(a, b, n - 2);
  printf("\n");
  
  return 0;
}

Output

Enter total number of terms: 10
Fibonacii series is : 0 1 1 2 3 5 8 13 21 34

Without using recursion

/*C program to print fibonacii series till N terms.*/

#include <stdio.h>

int main() {
  int a, b, sum, n;
  int i;

  a = 0;  // first term
  b = 1;  // second term

  printf("Enter total number of terms: ");
  scanf("%d", &n);

  printf("Fibonacii series is : ");
  // print a and b as first and second terms of series
  printf("%d\t%d\t", a, b);
  
  // run loop till n-2) terms because 2 terms already print
  for (i = 0; i < (n - 2); i++) {
    sum = a + b;  // calculate sum of a and b
    printf("%d ", sum);
    a = b;    // assign term second into a
    b = sum;  // assign sum of terms into b
  }
  printf("\n");
  
  return 0;
}

Output

Enter total number of terms: 10
Fibonacii series is : 0 1 1 2 3 5 8 13 21 34

C Recursion Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.