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
Post a Comment