How recursion occurs in the following code

2

I would like to understand, because I can not mentally glimpse what happens in the excerpt: return fat * factorial.fatorar (fat-1) ;, the question of recursion, regarding the calls of the factorar method itself in relation to multiplication with fat.

public class FatorialRecursiva
{   
   public static void main(String[] args)
   {
       FatorialRecursiva fatorial = new FatorialRecursiva();
       double dado = 5.0;
       dado = fatorial.fatorar(dado);

       System.out.print(dado);
   }

   public double fatorar(double fat)
   {
       if (fat < 2)
       {
           return 1;
       }else
       {
           return fat *  fatorar(fat-1);
       }
   }
}
    
asked by anonymous 16.04.2016 / 02:48

2 answers

9

Here is a gif that helps you to understand peacefully:

    
16.04.2016 / 04:35
0

Basically what happens is that a method executes itself. Because programming is object-oriented, code execution is not all linear and allows you to execute a single code snippet several times.

I recommend reading the article in which I extracted the following snippet, which uses as an example just the code that you used in the question:

" Recursion works similarly to a loop of repetition, in fact all that we do in loop, it can be done in recursion.Recursivity is nothing more nothing less than one function within another and it should be thought of as a stack.

    
16.04.2016 / 03:13