int x = 13;
while(x >= 4) {
if (x % 2 == 1) {
System.out.println(x);
}
x = x - 3;
}
I know the output of this, it is 13 and 7, would someone care to explain as how it came to be 13 and 7.
13 % 2 = 1 therefore, you print 13.
Now x = 10.
10 % 2 = 0, so you dont print out 10.
Now x = 7.
7 % 2 = 1, so you print 7.
Now x = 4.
4 % 2 = 0;
Now x = 1 and the loop stops.
The % operator is the modulo operator. This prints the remainder when dividing two numbers. For example 14/3 = 4 remainder 2, so 13 % 4 = 2.
case 1:
---> x = 13;
while(true) // 13 >= 4
if(true) // 13%2 = 1 which is 1==1 is true
then print x
reduce x by 3 // now x ==10
case 2 :
---> x = 10;
while(true) // 10 > =4
if(false) // 10 % 2 = 0, 0 == 1 is false
skip
reduce x by 3// now x == 7
case 3:
---> x =7;
while(true) // 7 > = 4
if(true) //7 % 2 ,1==1 is true
print x;
reduce x by 3 // x == 4
case 4:
---> x =4;
while(true) // 4 > = 4
if(false) //4 % 2 ,0==1 is false
skip
reduce x by 3 // x == 4
case 5:
---> x =1;
while(false) // 7 > = 4
skip
operator summary :
**%** finds remainder // result is undefined if RHS operand is 0
**>=** greater than or equals
%means? It's the modulus operator. To find out what the program does, follow the steps in your head, and write on a piece of paper what happens on each step.ifstatement basically means: "if x is odd".