RECURSIVE VERSUS ITERATIVE FACTORIAL
EXAMPLE PSEUDOCODE
function factorial is:
input: integer n such that n >= 0
output: [n × (n-1) × (n-2) × … × 1]
1. create new variable called running_total with a value of 1
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;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else
cout << number << " factorial is: " << factorial(number) <<
endl;
}
int factorial(int number) {
int temp;
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
}
EXAMPLE 2
#include <iostream>
unsigned long long factorial(unsigned long long n)
{
if (n == 0)
return 1;
else
return n * factorial (n - 1);
}
int main(void)
{
for (int n = 0; n <= 16; n++)
std::cout << n << "! = " << factorial(n) << std::endl;
return 0;
}
EXAMPLE 4 – TRY THIS TOO
#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;
}
}
EXAMPLE 5 – TRY THIS TOO
#include<iostream>
#include<conio.h>
using namespace std;
//Function
long factorial(int);
int main()
{
// Variable Declaration
int counter, n;
// Get Input Value
cout<<"Enter the Number :";
cin>>n;
// Factorial Function Call
cout<<n<<" Factorial Value Is "<<factorial(n);
// Wait For Output Screen
getch();
return 0;
}
// Factorial recursion Function
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
EXAMPLE 6 – TRY THIS TOO
#include <iostream>
using namespace std;
int factorial(int n) // 1, 1, 2, 6, 24, 120, 720, ...
{
if (n == 0) return 1;
return n * factorial(n-1);
}
main()
{
int n;
cout << "Enter a non-negative integer: ";
cin >> n;
cout << "Factorial of " << n << " is " << factorial(n) << endl;
return 0;
}
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