Learn Java Coding

Everything You Have To Know About Java

Recursion

Sometime do people refer to recursion as a picture in a picture in a picture etc. !THAT IS WRONG!recursion java

That makes the concept confusing. It is not a picture in a picture! It is a changing picture in a changing picture:

recursion java

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.

recursion java

 

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.

recursion java

So, you have to multiply your previous answer with the new answer.

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

recursion java

So, you have to:

  • Add a stop condition, cuz factorial calculates until 1. And when it reached that value it has to stop

recursion java

int factorial (int input) {
	if (input == 1) {
		return input;
	}
	return factorial(input – 1);
}

Next Post

Previous Post

© 2024 Learn Java Coding