Recursion

Hey guys i have a question about recursion im trying to learn it and i got stuck in the point where it hits the base case .
[code]
int factorial(int x)
{
if(x==1) return 1;
else return x*factorial(x-1);
}
5*4=20
4*3=12
3*2=6
2*1=2
and then it returns the value 1 and starts its way back up.
but how it work
Last edited on
closed account (EwCjE3v7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

// Once this function ends, it will return the value 1 if the value passed was 1 or higher
int factorial(int x)
{
	if(x==1) // 20 is not 1, 2nd time its 19, 3rd time it is 18 and so on
		return 1; // until the function stops calling itself and returns the value 1
	else
		return factorial(x-1); // so it takes 1 away from x, and with that value it calls itself
}

int main()
{	
	cout << factorial(20) << endl; // factorial is called with the value 20, this prints 1

	return 0;
} 
im sorry i forgot to put { x* factorial(x-1) this is a factorial problem
Topic archived. No new replies allowed.