# Learn Java Coding

Everything You Have To Know About Java

Sometime do people refer to recursion as a picture in a picture in a picture etc. !THAT IS WRONG! That makes the concept confusing. It is not a picture in a picture! It is a changing picture in a changing picture: as you can see; the pictures go from old to young

The second picture describes exactly what recursion is. In programming language you should say: You change the input every time you repeat the method. ### How can i play the same method and change the parameters all the time?

PRE-KNOWLEDGE: FACTORIAL

You have to think of this example. Calculating the factorial of a number. If you compute 5!, you calculate 5*4*3*2*1. Or you could formulate this problem in another way; 5 * (5-1) * (5-2) * (5-3) * (5-4). This is also the way to do this in java. You create a method and then redirect everything back to the method. Like this:

``````int factorial (int input) {
return factorial(input – 1);
}``````

RETURN – besides giving an output, can you also add a method in return.

### 1.

The method only returns the input in this case, Therefore, your answer is just the last value you will get as input. Now is your output: factorial(5) = 5 * factorial(5-1) = 120 factorial(4) = 4 * factorial(4-1) = 24 factorial(3) = 3 * factorial(3-1) = 6 factorial(2) = 2 * factorial(2-1) = 2 factorial(1) = 1 * factorial(1-1) = 1

So actually you do everything the other way around. This is what happens:

 factorial( ..) output = input times Previous output Previous output 1 * NO PREVIOUS OUTPUT = 1 2 * previous output = 2 3 * previous output = 6 4 * previous output = 24 5 * previous output = 120

### 2.

BUT the method keeps going, you need to stop when you have reached the desired result. Because at this moment you go from 5 to −∞ (minus infinity). So, you have to:

• Add a stop condition, cuz factorial calculates until 1. And when it reached that value it has to stop ``````int factorial (int input) {
if (input == 1) {
return input;
}
return factorial(input – 1);
}``````