Recursive Functions and Factorials

Feb 28, 2008 at 12:57pm
Okay so I'm writing a program for class and I can't seem to put my head around this.

The Code I got so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  
// Demonstrating the recursive function factorial.
#include <iostream>
using std::cout;
using std::endl;

#include <iomanip>
using std::setw;

unsigned long factorial( unsigned long ); // function prototype
void count_r2(int n);

int main()
{
	cout <<"By definition 0! = 1" << endl << endl;
 // calculate the factorials of 0 through 10
   for ( double counter = 0; counter <= 10; counter++ )
     { cout << setw( 2 ) << counter << "! = " << factorial ( counter )
         << endl;
	}


   return 0; // indicates successful termination
} // end main

// recursive definition of function factorial
unsigned long factorial( unsigned long number )
{
   if ( number <= 1 ) // test for base case
      return 1; // base cases: 0! = 1 and 1! = 1
   else // recursion step
      return number * factorial( number - 1 );
} // end function factorial

void count_r2(int n)
{
    if(n == 0)
        return;
    else
    {
        cout << n << " * ";
        count_r2(n-1);        
    }
        
}


and this outputs:



By definition 0! = 1

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800



But what I really want is 2! = 2 * 1, 3! = 3 * 2 * 1, etc. on the right side and then the answer

I think I have a function ready at the bottom but I'm not sure how to implement it properly and/if its correct at all for this situation.
Last edited on Feb 28, 2008 at 12:58pm
Feb 29, 2008 at 8:04pm
The count_r2 looks correct. Try just calling it; what does it print? Can you call that function and print something after it? Do some experimentation; you'll get it.
Feb 29, 2008 at 9:49pm
Here's a strong hint: count_r2() is doing a factorial except that it is also printing stuff to the screen. Therefore, except for the cout statements, it should look very much like the factorial() function...
Topic archived. No new replies allowed.