1
 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.

10
  • 6
    Do you know what % 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. Commented Apr 10, 2013 at 6:54
  • what's wrong with it, it is working fine, first it';; check for 13 and prints it, then for 10, and then for 7 and prints it and then for 4 Commented Apr 10, 2013 at 6:54
  • Substitute the value 13, 10 and so on for x . Now follow the statements and what it prints in your notebook. Commented Apr 10, 2013 at 6:55
  • i believe the % finds the reminder if i am correct. i understand where the 13 comes from but don't quite understand how it gives out a 7. Commented Apr 10, 2013 at 6:56
  • 4
    The if statement basically means: "if x is odd". Commented Apr 10, 2013 at 6:59

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhh i see , it was fairly simple, thanks for your answer will accept as soon as i can.
2

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.

Comments

2

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.