Can u guys help me with that? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

Can u guys help me with that?

i can't understand this code can someone explain it for me int y=60; int x=28; swich(y%4){ case 0 : case 1:y=y-10 ; break; case 2: case 3:y =y-5; break; }while(y>x) System.out.println(y);

4th Aug 2018, 9:29 AM
Sawen
Sawen - avatar
6 Answers
+ 6
thanks Matthias one question. :what will be happen if the code have hade break ?
4th Aug 2018, 2:12 PM
Sawen
Sawen - avatar
+ 5
Matthias thank you 🤗
4th Aug 2018, 4:13 PM
Sawen
Sawen - avatar
+ 5
hey Jang Jaeung thanks for your explanation... ^-^
15th Aug 2018, 8:49 AM
Sawen
Sawen - avatar
+ 4
y%4 gives you the remainder when you divide y/4 If the remainder is 0 or 1, you substract 10. If the remainder is 2 or 3, you substract 5. This is done until y is not any more larger than x. Note that cases without a break statement fall through the next one, until a break appears or reaches the end of the switch block. The final y is displayed.
4th Aug 2018, 9:41 AM
Matthias
Matthias - avatar
+ 3
You mean a break in case 0 and 2? Then it would stuck in an endless loop as no operation on y is performed. You can also try it in the code playground :)
4th Aug 2018, 4:05 PM
Matthias
Matthias - avatar
+ 3
I see that since the remainder for 60 / 4 is 0, it is the case for 0. then there is no break, so it keeps going on to the next case, where it is 1. now there, y is changed ti 50, and 10 is subtracted from it. there is break now, so the switch case ends. now there is while loop. as y is 50, and x is 28, it is true always. so the program keeps printing y over and over. //I knew that inside of if statement can be run without bracket if that is a single line, but did not know it is the same for while loop until I tested just now. thanks for letting me to figure this out :D // I was confused why the answered were so disorganized, and that was because it was sorted by vote. I have question about why you saying it stuck in an endless loop. No matter there are breaks after case 0 and case 2, current code is in endless loop. what changes is the value of y that is printed. Isn't it?? if there is break for case 0 and 2, then 10 is not subtracted, and prints 60. if no break, then 50.
14th Aug 2018, 8:07 PM
Jang Jaeung
Jang Jaeung - avatar