Pages

C++ Programming Tutorials - 15 (Recursions & Recursive Functions)

tut18.cpp =

// This tut contains Recursions & Recursive Functions in C++

#include<iostream>
using namespace std;

int fib(int n){
    if(n<2){
        return 1;
    }
    return fib(n-2) + fib(n-1);
}

int factorial(int n){
    if (n<=1){
        return 1;
    }
    return n * factorial(n-1);
}

// Step by step calculation of factorial(4)
// factorial(4) = 4 * factorial(3); 
// factorial(4) = 4 * 3 * factorial(2);
// factorial(4) = 4 * 3 * 2 * factorial(1);
// factorial(4) = 4 * 3 * 2 * 1;
// factorial(4) = 24;

int main(){
    
    // n! = n * (n-1)!
    int a;
    cout<<"Enter a number"<<endl;
    cin>>a;
    // cout<<"The factorial of "<<a<< " is "<<factorial(a)<<endl;
    cout<<"The term in fibonacci sequence at position "<<a<< " is "<<fib(a)<<endl;
    return 0;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Top 10 Python Packages Every Developer Should Learn

Top 10 Python Packages Every Developer Should Learn There are more than  200,000 Python packages  in the world (and that’s just counting tho...