# Please explain to me how this code work so it make sense to me.

• 12-16-2012
Meerul264
Please explain to me how this code work so it make sense to me.
Code:

#include <iostream>

using namespace std;

double factorial ( double a )
{
if (a > 1 )
return ( a * factorial (a -1) );
else
return (1);
}

int main()
{
double num;
cout << "Enter a number: ";
cin >> num;

cout << num << "! = " << factorial(num);

system("pause");
return 0;
}

Now I know that the working for factorial is

n! = n * ( n - 1) * ( n - 2) * ( n - 3) .... * 1

but I can't see how this is implemented on the code.

• 12-16-2012
manasij7479
Well, you have to realize that:
Code:

n! = n* (n-1)!
and that the factorual of 1 is always 1.
After that look at the factorial function, it'll be clear.
• 12-16-2012
grumpy
You are also aware that n! = n*(n-1)! if n is positive, and that both 0! and 1! are equal to 1?

So, if wanting to compute 4! one might calculate 4*3!. That requires calculating 3!, which is 3*2!. That requires calculating 2!, which is 2*1!. 1! is 1.
• 12-16-2012
Meerul264
Quote:

So, if wanting to compute 4! one might calculate 4*3!. That requires calculating 3!, which is 3*2!. That requires calculating 2!, which is 2*1!. 1! is 1.
I understand your point, but I still can't understand how the function can work it out like that.

This code is shown under the topic function (II), recursivity.

Maybe you can explain to me about recursivity briefly to explain how this work?

Thanks again.
• 12-16-2012
Salem
Code:

double factorial0 ( double a ) {
return 1;
}
double factorial1 ( double a ) {
return 1 * factorial0();
}
double factorial2 ( double a ) {
return 2 * factorial1();
}
double factorial3 ( double a ) {
return 3 * factorial2();
}
double factorial4 ( double a ) {
return 4 * factorial3();
}

It's like this, but without all the hassle of copy/paste/rename.
• 12-16-2012
Meerul264
And how does

Code:

double factorial0 ( double a ) {
return 1;
}
double factorial1 ( double a ) {
return 1 * factorial0();
}
double factorial2 ( double a ) {
return 2 * factorial1();
}
double factorial3 ( double a ) {
return 3 * factorial2();
}
double factorial4 ( double a ) {
return 4 * factorial3();
}

be similar with this?

Code:

double factorial ( double a )
{
if (a > 1 )
return ( a * factorial (a -1) );
else
return (1);
}

Sorry, after all that, I still need further explanation to understand.

• 12-16-2012
Meerul264
Ohh I get it now. So the work out s somewhat like..

if i put a = 5,

5 * ( factorial ( a -1 ))

then

5 * factorial ( 5 -1) same as a a* factorial ( a - 1)

5 * factorial (4)

then

5 * ( 4 * factorial ( 3 ) )

again [4 * factorial (3)] is same as [a*factorial(a-1)]

so

5 * 4 * ( 3 * factorial (2) )

5 * 4 * 3 * ( factorial (2) )

5* 4 * 3 * ( 2 * factorial ( 1 ) )

5 * 4 * 3 * 2 * 1 = 120..

Is my understanding correct?
• 12-16-2012
Salem
Yes, that's it.
• 12-16-2012
Meerul264
Alright thanks all.