Reputation: 37
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.
Upvotes: 1
Views: 803
Reputation: 2176
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
Upvotes: 2
Reputation: 19294
What don't you understand?
At the first iteration, x=13
, 13%2=1
so it prints 13
. The seconds iteration, x=10
(x=x-3
) 10%2=0
, nothing is printed. The third iteration x=7
(10-3
), 7%2=1
so 7 is printed.
After that, x=4 so nothing is printed and x=1
quits the loop.
Upvotes: 2
Reputation: 550
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
.
Upvotes: 2
Reputation: 120998
First x is 13, is it >= then 4? Yes. Enter the while loop. Is 13%2==1. Yes. Print x (print 13). Then x = x-13, x becomes 10. Is 10 >=4? Yes. .... So on.
Upvotes: 2