Need help creating this program in C++ Factorial Program Write a program to comp
ID: 3762532 • Letter: N
Question
Need help creating this program in C++
Factorial Program Write a program to compute the factorial of a number.
Factorial is defined as follows:
Fact(n) = n * (n-1) * (n-2) * (n-3) * ……. * 4 * 3 * 2 *1
For example: Fact(6) = 6 * 5 * 4 * 3 * 2 * 1 Implement the following Factorial program.
his C++ program asks a user to input non-negative integer number until the user chooses to quit (by entering a negative value).
The prompt can be: Please enter the next integer number. Enter -1 to quit:
Then compute the factorial of the number entered using two different methods: 1. Use a recursive method such that Fact(n) = n * Fact(n-1) 2.
Use an iterative method such that Fact(n) = 1 * 2 * 3 * …… n Display two outputs for each entered number:
1. Fact(n) is XXXX using the recursive method
2. Fact(n) is XXXX using the iterative method When a -1 is entered, the console displays “Press any key to continue…”
Explanation / Answer
/*
* C++ Program to Find Factorial of a Number using Iteration
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
/*
* Find Factorial of a Number using Iteration
*/
int fact_iter(int n)
{
ll result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
/*
* Main
*/
int main()
{
int n;
Boolean st=true;
while (st)
{
cout<<"Enter interger to compute factorial(0 to exit): ";
cin>>n;
if (n ==-1)
st=false;
int factter= fact_iter(n);
int factrec= factorial(n);
cout<<”Iterative method”<< factter <<endl;
cout<<”Recurssive method”<< factrec <<endl;
}
return 0;
}
int factorial(int number) {
int temp;
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.