Print the previous 30

Asked

Viewed 41 times

1

I have to print the 30 numbers previous to the number chosen by the user.

while(valor > (30 - valor)){
    System.out.println(valor);
    --valor;
}

I did so, but he does not print the previous 30, sometimes yes, sometimes no, where can I be missing? (has to be done with while).

1 answer

0


Creates an auxiliary variable, while the value is greater than or equal to itself minus 30, printa and decreases the value by 1. The problem with your code is that at the same time you validate yourself valor > 30-valor you also change within the while the value, that is, assuming that 60 is the value, at each loop it happens that:

1ª 60 > 30 - 60 //true

2ª 59 > 30 - 59 //Yes

3rd 58 > 30 - 58 //Yes

4th ...

With the auxiliary var it looks like this:

int aux = valor-30;
while(valor >= aux){
   System.out.println(valor);
   --valor;
}
  • 1

    Thanks for the answer!!! (sorry for the wording in the original question, I was not aware of the restrictions.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.