Q:

C program to print fibonacci series using recursion

0

C program to print fibonacci series using recursion

In this program, we will read value of N (N for number of terms) and then print fibonacci series till N terms 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 ...

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

fibonacci program 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to calculate power of a number using rec... >>
<< C program to find factorial using recursion....