0% found this document useful (0 votes)
21 views7 pages

What Is Factorial? N!: N! N× (N 1) × (N 2) × ×1

The document explains the concept of recursion in C++ through the example of calculating the factorial of a number. It details the recursive function structure, including the base and recursive cases, and provides a breakdown of the C++ code used to implement this functionality. Additionally, it discusses how stack frames work during recursive calls and the importance of having a base case to prevent infinite recursion.

Uploaded by

hjjo1732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views7 pages

What Is Factorial? N!: N! N× (N 1) × (N 2) × ×1

The document explains the concept of recursion in C++ through the example of calculating the factorial of a number. It details the recursive function structure, including the base and recursive cases, and provides a breakdown of the C++ code used to implement this functionality. Additionally, it discusses how stack frames work during recursive calls and the importance of having a base case to prevent infinite recursion.

Uploaded by

hjjo1732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

In C++, a recursive function is one that calls itself to solve a smaller instance of the

same problem. Let’s break down the concept and the code for calculating the
factorial of a number using recursion.

What is Factorial?
The factorial of a number n, denoted as n! is the product of all positive integers
less than or equal to n. Mathematically, it is expressed as:
n! = n×(n−1) × (n−2) ×⋯×1
For example:
 5! = 5×4×3×2×1=120
 0! = 1 (by definition)

Recursive Approach to Factorial Calculation


Recursion is a method where a function calls itself to break the problem down into
smaller subproblems. A recursive function generally has:
1. Base Case: The condition under which the recursion stops.
2. Recursive Case: The part where the function calls itself with modified
parameters.

Factorial Using Recursion


We can define the factorial of a number recursively as:
 Base Case: 0! = 1 (also true for 1! = 1).
 Recursive Case: For n > 1, n!=n×(n−1)!

C++ Code
C++ Code Breakdown

#include <iostream>
using namespace std;
This includes the standard I/O library needed for input (cin) and output (cout).

Defining the Recursive Function


int factorial(int n)
{
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
1. Base Case:
The condition if (n == 0 || n == 1) checks if n is either 0 or 1. In these cases,
the factorial is 1, so the function returns 1 and stops the recursion.
2. Recursive Case:
The expression return n * factorial(n - 1); is the key to recursion. Here’s
what happens:
o The function calls itself with n - 1, meaning it calculates the factorial
of the number just smaller than n, and multiplies it by n.
o This process continues until the base case (when n = 0 or n = 1) is
reached.

Main Function
int main()
{
int num;
cout << "Enter a number: ";
cin >> num;

// Calculate and display the factorial


cout << "Factorial of " << num << " is " << factorial(num) << endl;

return 0;
}

1. Input:
The user is prompted to enter a number using cin. The number is stored in
the variable num.
2. Factorial Calculations:
The factorial of the entered number is computed by calling the recursive
factorial function and passing num as the argument.
3. Output:
The calculated factorial is displayed using cout.
Example: How Recursion Works
Let’s trace the recursive calls for factorial (5):
1. First Call:
factorial (5) is called.
o Since 5 > 1, it computes 5×factorial (4)
2. Second Call:
factorial (4) is called.
o Since 4 > 1, it computes 4×factorial (3)
3. Third Call:
factorial (3) is called.
o Since 3 > 1, it computes 3×factorial (2)
4. Fourth Call:
factorial (2) is called.
o Since 2 > 1, it computes 2×factorial (1)
5. Fifth Call (Base Case):
factorial (1) is called.
o Since 1 ≤ 1, it returns 1.

Now the recursion starts returning values:

 factorial (2) becomes 2×1=2


 factorial (3) becomes 3×2=6
 factorial (4) becomes 4×6=24
 factorial (5) becomes 5×24=120

Thus, factorial (5) returns 120.


Key Points About Recursion:
 Function Stack: Every time the function calls itself, a new "stack frame" is
created. Once the base case is reached, these frames are resolved from the
innermost call back to the original.
 Termination: It’s crucial that the recursive function has a base case,
otherwise it would keep calling itself infinitely and lead to a stack overflow
error.

***A stack frame is a section of memory in the call stack (also known as the
execution stack or control stack) that stores information about a function call
during program execution. When a function is called, a new stack frame is created,
and it holds:
1. The function’s parameters: Any arguments passed to the function.
2. Local variables: Variables declared within the function.
3. Return address: The point in the program where the function should return
control after completing its execution.
4. Function's return value: The value that the function returns to the caller.
When a function finishes execution, its stack frame is removed (or "popped") from
the stack, and control is returned to the previous function or the calling function.
How a Stack Frame Works in Recursion
In a recursive function, like the factorial example we discussed, each recursive call
creates a new stack frame:
1. First Call: When factorial (5) is called, a stack frame is created that holds:
o The parameter n = 5.
o The return address where control should go back after calculating
factorial (5).
2. Recursive Call: factorial (5) calls factorial (4). This creates another stack
frame for factorial (4) with:
o Parameter n = 4.
o The return address for when factorial (4) finishes.
3. Next Calls: This process repeats for factorial (3), factorial (2), and factorial
(1). Each function call has its own stack frame holding the current value of n
and other relevant details.
4. Base Case (Termination): When factorial (1) is called, it hits the base case
and returns 1. The stack frame for factorial (1) is then removed.
5. Unwinding the Stack: After hitting the base case, the stack starts
"unwinding" as each previous stack frame completes and is removed:
o The result of factorial (1) (which is 1) is returned to factorial (2).
o Factorial (2) multiplies 2 by the returned value (1) and returns 2, then
its stack frame is removed.
o This process continues until the original call factorial (5) returns the
final result of 120.
Visualizing Stack Frames in Recursion
Here’s a simplified visualization of the stack frames for factorial (5):
Stack (top to bottom) during execution:

factorial (1) -> Returns 1, stack frame removed


factorial (2) -> Returns 2 × 1 = 2, stack frame removed
factorial (3) -> Returns 3 × 2 = 6, stack frame removed
factorial (4) -> Returns 4 × 6 = 24, stack frame removed
factorial (5) -> Returns 5 × 24 = 120, stack frame removed
Each of these frames holds the intermediate values and will be removed after the
function returns a value.
Key Points:
 The call stack keeps track of function calls and their execution order.
 Each stack frame is a snapshot of the function's current state during
execution.
 In recursion, multiple stack frames can be active at once, each representing a
different level of the recursive function call.
 The last-in, first-out (LIFO) nature of the stack means that the most recent
function call (the one at the top) is completed first before control is returned
to the previous one.

You might also like