This is called recursion. I think the bulk of the explanation is in What is a recursive method?.
There is a repetition yes, only there is a control command that says to repeat, the repetition happens precisely because the function call itself. If you call something over and over repeating the call.
As a structure as a while
or for
you know you should close the replay? There is a condition that decides this. In your role you also have a condition that decides when to stop the replay repetition to call the function again.
The comment in the code is right, but gives room for a wrong interpretation, so it gets better:
static int numeroBinario(int n) {
if (n > 0) { //o número ainda é maior que zero?
numeroBinario(n / 2); //repete a chamada
System.out.print(n % 2); //executa uma ação
}
return n;
}
It seems silly but on that line there was no condition, but the comment implied that there was a decision to be made. It may be that I understood it right, but it wasn’t written right. Programming is doing right all the time. Programming has no margin to do more or less, this is a human thing.
Realized I gave a simplified?
The same code written interactively:
int n = 120;
while (n > 0) { //o número ainda é maior que zero?
System.out.print(n % 2); //executa uma ação
n /= 2; //muda o próprio número
}
Actually this whole code is wrong. Or he should have one void
as return or he should take advantage of the value returned to continue making the calculation.
Even the method name is not good, because a method should indicate what it does and not what it is. This is better:
static void imprimeRepresetacaoBinariaParcial(int n) {
if (n > 0) {
ImprimeRepresetacaoBinariaParcial(n / 2);
System.out.print(n % 2);
}
return n;
}
Does it look too long? Yeah, but that’s what it is. Okay, I exaggerated a little bit because I wanted to make it clear that this is a representation and not a binary number.
Almost everyone learns wrong. Guilt from those who teach wrong because they learned wrong, so you have to be careful what you use to learn. Who learned wrong can only teach wrong.
Part of the long name is because this algorithm is best executed interactively and not recursively. Each run only prints a part of the total result so the name is wrong. And there’s no way to do it right recursively.
Something like that would be the code closest to ideal:
static void imprimeFormatoBinario(int n) {
while (n > 0) {
System.out.print(n % 2);
n /= 2;
}
}
I put in the Github for future reference.
See more in When to use recursion and when to use loops? and What is the advantage of using recursive functions?.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.
– Maniero