post  recursive factorial

kenryuakuma (44)   Link to this post
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream.h>

int factorial(int);

void main(void) {
	int number;
	
	cout << "Please enter a positive integer: ";
	cin >> number;
	if (number < 0)
		cout << "That is not a positive integer.\n";
	else
		cout << number << " factorial is: " << factorial(number) << endl;
}

int factorial(int number) {
	int temp;

	if(number <= 1) return 1;

	temp = number * factorial(number - 1);
	return temp;
}


Could somebody tell me step by step how this work? I have been spending a lot of hours figuring out. Somebody has told me how it works but it seems to be against the rule of programming. Really need this to proceed to the next chapter.
helios (6074)   Link to this post
the rule of programming
Which is...?
kenryuakuma (44)   Link to this post
NO not really the rule but is something confusing instead. So really hope you could help with this.
NGen (233)   Link to this post
I'm guessing that you mean that you thought it was on the list of things not to do, such as using goto statements.

Basically what is happening is that the function continually calls itself and decreases the number to factorial. When the number is less than or equal to 1, it stops calling itself and allows the chain of function calls to be completed. If we use factorial ( 5 );, we could look at operations that the program does like so:

- Call Factorial with 5
- Set variable to factorial of 5-1

- Call Factorial with 4
- Set variable to factorial of 4-1

- Call Factorial with 3
- Set variable to factorial of 3-1

- Call Factorial with 2
- Set variable to factorial of 2-1

- Call Factorial with 1
- The number for factorial is equal to 1, return 1

- Return 2*1
- Return 3*2
- Return 4*6
- Return 5*24
Last edited on
kenryuakuma (44)   Link to this post
I really need a step by step guide to show me how this works because it is so confusing. Forget about the rule of programming in my earlier post, and really wanna get down to the core of it. I really appreciate it if you guys would.
ALMaestro (3)   Link to this post
hi
i can tell you about your question
but i am sorry my English is so bad

I can tell you only in Arabic language

my best regards
firedraco (2622)   Link to this post
If you have a debugger, you could step through the code and see what it is doing. Just make sure to step into the factorial function.
kenryuakuma (44)   Link to this post
It would be great if some of you are willing to tell me as I don't have anything home except I could do this in school. But computers are not always available.

This topic is archived - New replies not allowed.