Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ program on visual studio. Complete this program by adding a recursive functi

ID: 3804146 • Letter: C

Question

C++ program on visual studio.

Complete this program by adding a recursive function to calculate n-factorial (n!). Recall that n! is n * (n - 1) * (n - 2) * ... 2 * 1. Note that a special case is that 0! is defined as 1. Be sure to check that your answers are correct. You should find they are wrong for values of n > 12; they will be for the looping version, which uses an int. Explain why that is in the comments at the top of the program. This program is in the lecture slides... if you're stuck, look at the slides (in Course Materials), but don t copy/paste... write it yourself from scratch.

Explanation / Answer

#include <iostream>

using namespace std;

/*
*This will return corect value only upto n = 12 because after that int is not able to hold the values properly
* Using long instead of int can handle little larger range.
* */
int factorial(int n)
{
if (n == 0 || n == 1) return 1;
else
return n*factorial(n-1);
}

int main()
{
int n;
while(true)
{
cout << "Enter a number to compute its factorial: ";
cin >> n;
if (n < 0)
cout << "Enter a numbergreater than or equal to 0" << endl;
else
break;
}

int facN = factorial(n);
cout << "Factorial of "<< n << " is " << facN << endl;
return 0;
}

/*

Sample run
Enter a number to compute its factorial: 10
Factorial of 10 is 3628800
*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote