Group
Functions in C++
Objective
1. Create a function named factorial that takes an integer as input.
2. Use an if statement to define the base case: if the number is 0, return 1.
3. For the recursive case, return n multiplied by the factorial of n - 1.
4. In the main function, prompt the user to enter a number.
5. Call the recursive function and display the result.
Implement a recursive function to calculate the factorial of a number.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Recursive function to calculate the factorial of a number
int factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
}
return n * factorial(n - 1); // Recursive call
}
// Main function
int main() {
int number;
// Ask the user to enter a number
cout << "Enter a non-negative integer: ";
cin >> number;
// Check if the number is negative
if (number < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
// Call the recursive factorial function and print the result
int result = factorial(number);
cout << "Factorial of " << number << " is: " << result << endl;
}
return 0; // End of the program
}
Output
Enter a non-negative integer: 5
Factorial of 5 is: 120