C C++ program to generate fibonacci series using recursion

Coding in C

#include<stdio.h>
int fab(int);
int main()
{
    int n, i;
    printf("Enter n: ");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    printf("%d\n",fab(i));
    return 0;
}
int fab(int x)
{
    if(x==1)
        return 0;
    else if(x==2)
        return 1;
    else
        return fab(x-1)+fab(x-2);
}

Coding in C++

#include<iostream>
using namespace std;
int fab(int);
int main()
{
    int n, i;
    cout<<"Enter n: ";
    cin>>n;
    for(i=1;i<=n;i++)
    cout<<fab(i)<<endl;
    return 0;
}
int fab(int x)
{
    if(x==1)
        return 0;
    else if(x==2)
        return 1;
    else
        return fab(x-1)+fab(x-2);
}

Output

C C++ program to generate fibonacci series using recursion

Published by

admin

I am a computer teacher, programmer and web developer