Recursive Factorial in C++ Example of Code for CLASS PRACTICE
Recursive Factorial in C++ Example of Code for CLASS PRACTICE
EXAMPLE PSEUDOCODE
2. begin loop
1. if n is 0, exit loop
2. set running_total to (running_total × n)
3. decrement n
4. repeat loop
3. return running_total
end factorial
C++ CODES
example 1
#include <iostream.h>
int factorial(int);
void main(void) {
int number;
EXAMPLE 2
#include <iostream>
int main(void)
{
for (int n = 0; n <= 16; n++)
std::cout << n << "! = " << factorial(n) << std::endl;
return 0;
}
#include <iostream>
using std::cin;
using std::cout;
int fac(int);
int main()
{
// Prompt, get input
cout << "\nFactorial, enter a nonnegative integer: ";
int non_neg_int;
cin >> non_neg_int;
// Compute factorial
int factorial = fac(non_neg_int);
// Output result
cout << "The factorial of "
<< non_neg_int
<< " is "
<< factorial
<< ".\n\n";
return 0;
}
//------------------------------------------------------------------------
/** Nonnegative int argument required.
* Compute and return the factorial of the argument,
*/
int fac(int num)
{
if (num == 0)
// Base case, by definition of 0!
return 1;
else
{
// Recursive case
int factorial = num * fac(num - 1);
return factorial;
}
}
#include<iostream>
#include<conio.h>
//Function
long factorial(int);
int main()
{
// Variable Declaration
int counter, n;
#include <iostream>
using namespace std;
main()
{
int n;
FLOW CHART
SIMPLE IMPLEMENTATION OF ITERATIVE FACTORIAL PSEUDOCODE
EXAMPLE 1
\\ Factorial module
ENTER n
nFac = 1
WHILE n > 0 DO
nFac = nFac * n
n = n - 1
ENDWHILE
RETURN nFac
EXAMPLE 2
ans = 1
for i = n down to 2
ans = ans * i
next