Recursive Factorial
Part of the Logic & Flow section of Coddy's C++ journey — lesson 46 of 56.
The factorial of a number is a perfect example to demonstrate recursion in action. The factorial of n (written as n!) is the product of all positive integers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
What makes factorial ideal for recursion is that it can be defined in terms of itself: n! = n × (n-1)!. This means to calculate 5!, you multiply 5 by 4!, and to calculate 4!, you multiply 4 by 3!, and so on.
Here's how a recursive factorial function looks:
int factorial(int n) {
if (n <= 1) { // Base case: 0! and 1! both equal 1
return 1;
}
return n * factorial(n - 1); // Recursive step: n! = n × (n-1)!
}The base case stops the recursion when n reaches 1 or 0, returning 1. The recursive step multiplies the current number by the factorial of the next smaller number. When you call factorial(4), it calculates 4 × 3 × 2 × 1 by making successive calls until it reaches the base case, then multiplies all the results together as the calls return.
Challenge
EasyCreate a program that implements a recursive factorial function and uses it to calculate factorials for different input values. This challenge will test your understanding of how recursion works by having a function call itself with modified parameters until it reaches a base case.
The following input will be provided:
- An integer
nrepresenting the number for which to calculate the factorial
Your program should:
- Create a recursive function named
factorialthat takes an integer parameter and returns an integer - The function should implement the base case: if
nis less than or equal to 1, return 1 - The function should implement the recursive step: return
nmultiplied by the factorial ofn-1 - In the main function, read the input value
- Call the factorial function with the input value
- Print the result using the specified format
Use the following exact output format:
Factorial of [n] is [result]Remember that the factorial function must call itself with a smaller value each time, moving closer to the base case with each recursive call. The base case prevents infinite recursion by stopping when n reaches 1 or 0. The recursive step multiplies the current number by the factorial of the next smaller number, building up the final result as the function calls return their values.
Cheat sheet
The factorial of n (n!) is the product of all positive integers from 1 to n. It can be defined recursively as: n! = n × (n-1)!
Recursive factorial function:
int factorial(int n) {
if (n <= 1) { // Base case: 0! and 1! both equal 1
return 1;
}
return n * factorial(n - 1); // Recursive step: n! = n × (n-1)!
}The base case stops recursion when n reaches 1 or 0. The recursive step multiplies the current number by the factorial of the next smaller number.
Try it yourself
#include <iostream>
using namespace std;
// TODO: Write your factorial function here
int main() {
// Read input
int n;
cin >> n;
// TODO: Call the factorial function and store the result
// Output the result
cout << "Factorial of " << n << " is " << result << endl;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice4Maps (Key-Value Pairs)
Introducing std::mapCreating a MapAccessing and Modifying ValuesChecking for KeysRemoving PairsIterating Over a MapRecap - Word Frequency7Advanced Functions
Pass by ReferenceIntro Lambda ExpressionsLambdas with ParametersLambdas with Return ValuesIntroduction to RecursionRecursive FactorialLambda Sort2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items