ADVERTISEMENT
ADVERTISEMENT

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 ...

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

C Recursion Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.