**Factorial(X)** is the sum of multiplying all numbers from 1
to X. This calculation problem can be simply solved through recursion like shown
below :

public int Factorial (int x){
if(x == 0){
return 1;
}
else {
return x * Factorial (x-1);
}
}

This method takes an integer (int) as input and gives out another integer as an
output.

**First**, we have to
determine the basic case. In this example it will be when the
multiplied number is 0 then the result is 1. Which means
that when 0 is sent to the method the output will be 1.

**If the method does not receive a 0**, the method will follow the other option. The value of i wil be stored and multiplied by it's previous
value.

x*(x+1)

with 'i' being the current value of 'x' and 'x+1' it's previous value since we're
substracting 1 for each iteration.

The method will then call itself again with an update 'x-1' .**This update is crucial**
otherwise the method will keep calling itself **forever** since it won't be able to
meet the required condition to stop the loop when. That condition is met only when :

x == 0

Let's look at this example to clear things up. Let's suppose that we called the
method like this :

System.out.println(Factorial(4));

In the *first call* 4!=
0, so we follow the next step:

4 * Factorial(4-1)

*Second call* will give us this
result:

3 * Factorial(4-1)

Then the *third call*:

2 * Factorial(2-1)

And finally, the
*fourth
call*:

1 * Factorial(1-1)

During the fifth call, i==0, so **our condition is fulfilled**. The value 1 will be
returned to the last call.

One of the things to keep in mind, is that in case the method has called itself
more than one time, **the calls will
be kept in a stack** so that the *last call gets the first answer*.
Let's take a look at the figure below:

Like we did in the previous example, we're going to create a method that takes an
integer value ('X') and calculate the sum of all numbers from 0 to X.

public int SUM(int x)
{
if(x == 0)
{
return 0;
}
else
{
return x + SUM(x -1);
}
}

Here, the user selects the value of X and we're displaying numbers from X to 1 in
a descending order

public void printInt(int x)
{
if(x == 1)
{
System.out.println(1);
}
else
{
System.out.println(x);
printInt(x-1);
}
}

However, if we wanted to display the numbers in an
ascending order. All we have to do is change the order of the last 2
lines like shown below :

public void printInt(int x)
{
if(x == 1)
{
System.out.println(1);
}
else
{
printInt(x-1);
System.out.println(x);
}
}