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

Load a Pandas dataframe with a selected dataset. Identify and count the missing values in a dataframe. Clean the data after removing noise as follows: a. Drop duplicate rows. b. Detect the outliers and remove the rows having outliers c. Identify the most correlated positively correlated attributes and negatively correlated attributes

The weights of 8 boys in kilograms: 45, 39, 53, 45, 43, 48, 50, 45. Find the median

Download any dataset and do the following: a. Count number of categorical and numeric features b. Remove one correlated attribute (if any) c. Display five-number summary of each attribute and show it visually