473,848 Members | 1,691 Online

# nonrecursive, iteration

1 New Member
I wrote this program to calculate factorials by recursion, how would I make it nonrecursive and iterative?
Thank you to whom ever may be of assistance

#include <iostream>

using std::cout;
using std::endl;

#include <iomanip>

using std::setw;

unsigned long factorial( unsigned long ); // function prototype

int main()
{
// Loop 10 times. During each iteration, calculate
// factorial( i ) and display result.
for ( int i = 0; i <= 10; i++ )
cout << setw( 2 ) << i << "! = "
<< factorial( i ) << endl;

return 0; // indicates successful termination

} // end main

// recursive definition of function factorial
unsigned long factorial( unsigned long number )
{
// base case
if ( number <= 1 )
return 1;

// recursive step
else
return number * factorial( number - 1 );

} // end function factorial
Oct 27 '06 #1
1 1886
arne
315 Recognized Expert Contributor
I wrote this program to calculate factorials by recursion, how would I make it nonrecursive and iterative?
Thank you to whom ever may be of assistance

#include <iostream>

using std::cout;
using std::endl;

#include <iomanip>

using std::setw;

unsigned long factorial( unsigned long ); // function prototype

int main()
{
// Loop 10 times. During each iteration, calculate
// factorial( i ) and display result.
for ( int i = 0; i <= 10; i++ )
cout << setw( 2 ) << i << "! = "
<< factorial( i ) << endl;

return 0; // indicates successful termination

} // end main

// recursive definition of function factorial
unsigned long factorial( unsigned long number )
{
// base case
if ( number <= 1 )
return 1;

// recursive step
else
return number * factorial( number - 1 );

} // end function factorial
Try
Expand|Select|Wrap|Line Numbers
1. long fac( long n ) {
2.
3.     long res = 1;
4.
5.     for( long i=n; i>0; i-- ) {
6.
7.         res *= i;
8.     }
9.
10.     return res;
11. }
12.
Should do it.
Oct 27 '06 #2