-
calculating iteratively
My program is suppost to show the factorial of a number loop 10 times. During each iteration, calculate
// factorial ( i ) and display results.
Now I need to be able to do this by adding a function to the code to do it iteratively.
this part works but i need to add a nonrecursively function to it
Code:
// recursive
// written by
// cis
#include <iostream>
#include <iomanip>
using namespace std;
unsigned long factorial ( unsigned long );
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;
}
unsigned long factorial ( unsigned long number )
{
// base case
if ( number <= 1 )
return 1;
// recursive step
else
return number * factorial ( number - 1 );
}
now this part will figure it nonrecursively
Code:
factorial = 1;
for ( int counter = number; counter >= 1; counter-- )
factorial *= counter;
here is where i'm having problems I can't get it to run properly
this is what i have so far
sorry for the amount of code
any hints in the right direction would be appreciated
Code:
// recursive.cpp
// written
// cis
#include <iostream>
#include <iomanip>
using namespace std;
unsigned long factorial ( unsigned long );
int factorial1 ( int, int );
int main()
{
int f = 0,
factor = 1;
// loop 10 times. During each iteration, calculate
// factorial ( i ) and display results.
for ( int i = 0; i <= 10; i++ )
cout << setw ( 2 ) << i << "! = "
<< factorial ( i ) << endl;
cout << "! = " << factor << endl;
return 0;
} // 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
factorial1 (int number,int factor )
{
for ( int counter = number; counter >= 1; counter-- )
factor *= counter;
while (counter <= 10 );
return factor;
}
-
Sorry I can't help maybe this will.
-
here, try this:
Code:
int factorial1 (int number,int &factor )
{
int counter;
for(counter = number; counter > 0; --counter) {
factor *= counter;
}
}
Making factor a reference parameter would be the easiest way. you would have to cout factor in main though. the way you have it, once the return is hit, it is out of the fxn. it won't keep returning until the counter is done. once one return statement is hit, the fxn is done.
this also assumes that factor is passed as one to begin with.