#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.
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
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.
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.