What is recursion in Java, some kind of complete, incomprehensible crap, let's go over it.
Example:
public class Recursion {
public static void main(String[] args) {
System.out.println("Изначальный REC ( 15 , 9 )" );
System.out.println(rec(15,9)); // запускаем sout с возвращаемым функцией [rec] результатом
}
static int rec (int m, int n) { // передаем в функцию [rec] 2 числа
if(m % n == 0) { // если первое число [m] делится на второе число [n] нацело, то возвращаем его
System.out.println("Окончателное число " + n);
return n;
} else {
// если не делится нацело, то перезапускаем функцию и заносим в него другие аргументы :
// в качестве первого уже будет второе число [n],
// а в качестве второго будет остаток от деления первого[m] на второе[n] 15 / 9 = 1 (+ остаток 6)
System.out.println("Заносим в REC (" + n + " , " + m % n + ")");
return rec(n,m % n);
}
}
You can copy this code and test it yourself. Description of what happens inside with the variables: initially 15, 9
divided 15 / 9 = 1
, remainder 6
, if there is a remainder, then the new function is launched, but the values will already be 9, 6
(from the remainder) is divided 9 / 6 = 1
, remainder 3
, if there is a remainder, then the new function is launched, but the values will already be 6, 3
(from remainder) is divided 6 / 3 = 2
, remainder 0
if there is no remainder, the second number is output from the function 3
. Now let’s look at everything in more detail, for my grandmother.
- Recursion in Java is running a function from within the function itself.
- When a function is launched, everything that was done inside the function is erased and a new function is launched, with new parameters.
GO TO FULL VERSION