24 Computer -- Programming Concepts and Logics

ask mattrab Visit www.askmattrab.com for more academic resources.

C++ program to print Fibonacci sequence || Recursive and Iterative


//print fibonacci series upto nth term
#include<bits/stdc++.h>
using namespace std;

 //using recursion
int fibonacci(int n){
    if (n==0){
        return 0;
    }
    if (n==1){
    return 1;
    }
    return fibonacci(n-1)+fibonacci(n-2);
}

//using iteration
    int fibonacci2(int n){
    int a=0,b=1,c;
    if (n==0){
        return a;
    }
    if (n==1){
    return b;
    }
    for (int i = 2; i <=n; i++)
    {
        c=a+b;
        a=b;
        b=c;
    }
    return c;
}

int main(){
    int n;
    cout<<"enter the number of terms";
    cin>>n;
    while (n--)
    {
        int a;
        cin>>a;
        cout<<fibonacci(a)<<endl;
    }
}


Input: 5

output: 0 1 1 2 3

Discussions

More notes on Programming Concepts and Logics

Close Open App