Please do it in c++, will up vote!!
create a recursive function to perform a factorial calculation.
- int factorial(const int value)
- return -1 if any negative number passed into the function
- Calculate the factorial of the number entered by the use
Determine value at which stack overflow occurs.
The code followes will do the requirements specified in the question. Everey steps are explained using comments.
1) is without stack overflow and 2) is with stack overflow.
1) The code below will determine the factorial of a number without stack overflow:
#include<iostream>
using namespace std;
int factorial(const int n); //declaring factorial function
int main()
{
int n; //declaring integer to get user input
//asking student for input
cout << "Enter a Integer: ";
cin >> n; //getting user iput to n
//printing message and factorial calling fact function
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
//defining fact function recrussive
int factorial(const int n)
{
//cheking if number is 2 or greater
if(n > 1)
return n * factorial(n - 1); //recrussively calling fame function by number-1
//checking if the number entered is -ve
else if(n < 0)
return -1; //if entered -ve number returning -1
else
return 1; //if number is 0 or 1 factorial = 1
}
OUTPUT (when enter a positive integer):
OUTPUT (when enter a -ve number):
OUTPUT (when entering 0 and 1):
2) The code below will determine the factorial when stack overflow occurs: (ie If the base case is not reached or not defined, then the stack overflow problem may arise.) In our case, if the return value is not defined for n =< 1 (factorial of 1 and 0 is 1), the stack overflow will raise. Check the code and output below for further clarification.
#include<iostream>
using namespace std;
int factorial(const int n); //declaring factorial function
int main()
{
int n; //declaring integer to get user input
//asking student for input
cout << "Enter a Integer: ";
cin >> n; //getting user iput to n
//printing message and factorial calling fact function
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
//defining fact function recrussive
int factorial(const int n)
{
//cheking if number is 2 or greater
if(n > 1)
return n * factorial(n - 1); //recrussively calling fame function by number-1
}
OUTPUT (when entering 3(+ve integer not 0 and 1)):
OUTPUT (when entering 0):
this answer is wrong cause factorial of 0 is 1. this is the problem with the stack overflow.
OUTPUT (when entering 1):
this remains same. and the answer is correct.
Get Answers For Free
Most questions answered within 1 hours.