Converting recursive function into a loop

I am trying to convert a recursive function into a for loop but it is not working properly. Please advise. Thank you for your help!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

//recursive function (works properly)
int factorial(int n, int acc = 1)
{
	if (n == 1)
		return acc;
	else
		return factorial(n - 1, acc*n);
}

//converting recursive function into a loop (not working)
int factorial(int n)
{
	int acc = 1;
	for (; n > 1; --n){
		acc *= n;
		return acc;
	}

}
Explain line 17.
that is just returning the final value.

i actually got it to work by doing a while loop.

1
2
3
4
5
6
7
8
9
10
11
12
int factorial(int n)
{	int num = n;
	int acc = 1;
	while(num != 1)
	{
		acc = acc * num;
		num = num - 1;
		
	}
	
	return acc;
}
also got it to work with the for loop!

1
2
3
4
5
6
7
8
9
int factorial(int n)
{
	int acc = 1;
	for (; n >= 1; --n){
		acc *= n;
	}

	return acc;
}
Topic archived. No new replies allowed.