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
now this part will figure it nonrecursivelyCode:// 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 ); }
here is where i'm having problems I can't get it to run properlyCode:factorial = 1; for ( int counter = number; counter >= 1; counter-- ) factorial *= counter;
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; }



LinkBack URL
About LinkBacks


