simulation

i have nothing to do,i just scanning every tutorials i learnt but i just notice i find it confusing about the simulation of this code
why this code the function factorial call himself inside?
can you explain the simulation of this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

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

int main ()
{
  long number = 9;
  cout << number << "! = " << factorial (number);
  return 0;
}
Last edited on
You know what factorial is?

5! = 5 × 4 × 3 × 2 × 1

Notice 4 × 3 × 2 × 1 = 4! so we can write it as

5! = 5 × 4!

We could be more general and write it for any positive integer n

n! = n × (n - 1)!

Notice how we have used factorial to define what factorial means. There is only one thing missing. We need to define the special case 1! (or 0!), otherwise the calculation would go on for ever. That's why you have the if statement in your code.
Last edited on
i knew about factorial

its not that. my question is in the function factorial. why the factorial function called inside of the factorial fucntion
why the factorial function called inside of the factorial fucntion

Peter87's post explains that:
"n! = n × (n - 1)!"
Factorial is often used to demonstrate recursive functions (functions that calls themselves). Recursion is one way of doing it. Another way is to use a loop.
There is only one thing missing

it is okay. on my compiler it isn't computing negative numbers it stops in 0.





@Chervil
sorry i did not notice . because i thought he would just explain about factorials hehe
it's clearer now
@Peter87 @Chervil Thanks
justinelandichoruiz wrote:
>There is only one thing missing
it is okay. on my compiler it isn't computing negative numbers it stops in 0.

I didn't mean something is missing from your code. I just meant that if factorial is defined as simply n! = n × (n - 1)! then there is something missing.
Last edited on
haha sorry sorryy. im just so dizzy right now because its about 9 hours im studying today.
Last edited on
Topic archived. No new replies allowed.