?Trying to print out the factorial (n!) process

Hi,

I am trying to print out the Factorial process such as 6!:
Console output:
Function returned: 6! = 1*2*3*4*5*6 = 720

However, I couldn't figure it out. There are two kind of problems in my code: when the loop finishes, I get one extar "star" like [...] 6*; the outputs order is not as I want it to be.

I have tried two ways; niether of them work as I want.

First way:
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
#include <iostream>

using namespace std;

int factorial (int num);

int main ()
{
	int n;



	cout << "Enter a number and press Enter: ";
	cin >> n;
	cout << endl;

	cout << "Function returned: " << factorial (n) << " = " << n << "! = " ;
	cout << endl;
	cout << endl;
	
	return 0;
}


int factorial (int n)
{
	int i;
	int sum = 1;

	for (i = 1; i <= n; i++)
		{
			sum = sum * i;
			cout << i<< "*";
		
		}

	return sum;
}

Its output:

Enter a number and press Enter: 6

1*2*3*4*5*6*Function returned: 720 = 6! =

Press any key to continue . . .


Second way:
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
#include <iostream>

using namespace std;

int factorial (int num);

int main ()
{
	int n;



	cout << "Enter a number and press Enter: ";
	cin >> n;
	cout << endl;

	cout << "Function returned: " << factorial (n) << " = " << n << "! = " ;
	cout << endl;
	cout << endl;
	
	return 0;
}


int factorial (int n)
{
	int i;
	int sum = 1;

	for (i = 1; i <= n; i++)
		{
			sum = sum * i;
			cout << i;
		
		}

		for (i = 2; i <= n; i++)
		{
			
			cout << "*";
		
		}

	return sum;
}

Its output:

Enter a number and press Enter: 6

123456*****Function returned: 720 = 6! =

Press any key to continue . . .


Thanks in front,
Using your first implementation, simply don't output another * if you are going through the loop for the last time.
That's what I am trying to figure it out, but I couldn't. If I change the count strarts the factorial result would be wrong since one loop would be missing.
I didn't say change the count. What will the value of i be the last time the loop executes?
If it is 6!, the last value of "i" would be 6, but I don't know how it is related to number of "*" output.
Last edited on
Just use continue, to skip the last '*'.

Edit: There's also another simple way. Try to find it.
Last edited on
Thanks guys. I just decreased the loop by one; output the last number outside the loop.
That works. The solution we were hinting at was this:

1
2
3
4
5
6
for (i = 1; i <= n; i++)
{
    sum = sum * i;
    if( i != n  )   // Last time through this loop, i == n (because i + 1 is > n, loop terminates)
        cout << i<< "*";
}


Topic archived. No new replies allowed.