JavaRush /Java Blog /Random EN /Recursion in a nutshell
vinsler
Level 35

Recursion in a nutshell

Published in the Random EN group
What is recursion in Java, some kind of complete, incomprehensible crap, let's go over it.
Recursion in a nutshell - 1
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.
  1. Recursion in Java is running a function from within the function itself.
  2. When a function is launched, everything that was done inside the function is erased and a new function is launched, with new parameters.
In other words, if you see the word launch of the same function [rec], then take this function at the very beginning of its description, transfer the supplied parameters there and see what happens next. That's all the explanation. We run the function, set certain parameters inside, at which either the recursion is started or some result is returned. That's the whole secret. PS: I wrote just from my head, right away and helped a friend for one thing, so all criticism and improvements are welcome. )))
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION