Implement following recursive functions: a. Factorial of a number b. Nth fibonacci number

Implement following recursive functions:
a. Factorial of a number
b. Nth fibonacci number





 #include <iostream>

using namespace std;


// Recursive function to calculate the factorial of a number

int factorial(int n) {

    // Base case: factorial of 0 is 1

    if (n == 0) {

        return 1;

    }


    // Recursive case: multiply n with factorial of (n-1)

    return n * factorial(n - 1);

}


// Recursive function to calculate the nth Fibonacci number

int fibonacci(int n) {

    // Base cases: Fibonacci numbers for n = 0 and n = 1 are 0 and 1 respectively

    if (n == 0) {

        return 0;

    }

    if (n == 1) {

        return 1;

    }


    // Recursive case: sum of the previous two Fibonacci numbers

    return fibonacci(n - 1) + fibonacci(n - 2);

}


int main() {

    int number;


    // Factorial

    cout << "Enter a number to calculate its factorial: ";

    cin >> number;

    int fact = factorial(number);

    cout << "Factorial of " << number << " is: " << fact << endl;


    // Fibonacci

    cout << "Enter a number to calculate its Fibonacci number: ";

    cin >> number;

    int fib = fibonacci(number);

    cout << "The " << number << "th Fibonacci number is: " << fib << endl;


    return 0;

}


Comments

Popular posts from this blog

Using Titanic dataset, do the following: a. Find total number of passengers with age less than 30 b. Find total fare paid by passengers of first class c. Compare number of survivors of each passenger class

Differentiate between Unimodal, Bimodal and Multimodal with graphic representation.

Import iris data using sklearn library . Compute mean, mode, median, standard deviation, confidence interval and standard error for each feature ii. Compute correlation coefficients between each pair of features and plot heatmap iii. Find covariance between length of sepal and petal iv. Build contingency table for class feature