0
What is i%2?? Why x is 9 and y is 6?
int x=0, y=0; for (int i=0; i<=5; i++) if (i%2==0) for (int j=0; j<5; j++) if (j%2==0) x++; else y++; Qual `e il valore finale delle variabili x e y? x = 9, y = 6
4 Antworten
+ 3
Ivan Ferro
i % 2 gets 0 for even numbers. Because every even number is divisible by 2.
First loop runs from 0 to 5.
even i's: 0, 2, 4
Second loop rums from 0 to 4.
even j's 0, 2, 4
i = 0 -> increment x when j = 0 or 2 or 4 //3 times: x gets 3
Same for i = 2 //x gets 6
Same for i = 4 //x gets 9
i = 0 -> increment y when j = 1 or 3 //2 times: y gets 2
Same for i = 2 //y gets 4
Same for i = 4 //y gets 6
For i = 1, 3 or 5 the second loop will not start. Nothing happens with x or y.
+ 3
Ivan Ferro Your welcome :)
I recommend using curly brackets.
for(int i = 0; i <= 5; i++){
if(i % 2 == 0){
for(int j = 0; j < 5; j++){
if(j % 2 == 0){
x++;
}else{
y++;
}
}//end second loop
}//end first if
}end first loop
The curly brackets creates blocks. Everything inside a block belongs together.
Over time you will learn which ones you really need and which ones you can leave out. But for me when I started to learn java it was helpful to use them for every loops/if statements
+ 1
Denise Roßberg Thank you, now i understand!
0
% it is modulo division. The result of this is the rest of the division.
Now try again, what happens here, and count x and y. If you get stuck then let me know.