1

Okay I have got following for loop:

  public static void main(String []args){
        for (int i=2; i<12 ; i=i+2)
        System.out.print(3-i%3);
        System.out.println();
     }

And it is printing out: 12312. In order to understand how it calculates the numbers I have tried to work it out and according to my working it out the first number should be actually 2.

I am pretty sure, I am wrong with my thinking since BlueJ prints out firstly number 1. But why 1? Can someone explain it?

I have written on a piece of paper the way how I understood/work out the calculation and took a picture of it so you can see my working of getting the number 2 and maybe you can point out my mistake.

enter image description here

9
  • "according to my working it out the first number should be actually 2" 3-2%3 = ? (% is the modulus operator) Commented May 1, 2014 at 17:52
  • 5
    cutest ... notes ... ever ! :D Commented May 1, 2014 at 17:53
  • 2
    i = 2; i % 3 = 2; 3 - 2 = 1 Commented May 1, 2014 at 17:55
  • 2
    @Acemi But the increment step is done after each iteration. Commented May 1, 2014 at 18:00
  • 1
    @Acemi In the first iteration, i = 2. In the second, i = i + 2 = 2+2 = 4. In the third, i = i +2 = 4 + 2 = 6. In the fourth , i = i +2 = 6 +2 = 8.. and so on till i<12. Commented May 1, 2014 at 18:00

2 Answers 2

3

according to my working it out the first number should be actually 2.

Check your calculations: 2 % 3 (the remainder after dividing 2 by 3) is 2. 3 - 2 is 1, so the output is correct.

Note that the operations are not performed in the order in which they are written out: % has higher precedence than subtraction, so it is performed before subtraction. It does not matter in this case, but it is an important thing to keep in mind.

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

Comments

2

Based on your notes , I think you misunderstood the behavior of for loop.

As per your notes, you substitute i as 4 ( 2+2) in the first iteration.

 for (int i=2; i<12 ; i=i+2)

But , for the first iteration i will be 2

initial value ; condition ; increment/decrements

end of each iteration the third block will execute (increment/decrements) . So for the first iteration i would be 2

and 3-i%3 w would be 3-(2%3) => 3 - 2 => 1 .

For the next iteration i would be i = i+2 => 2 + 2 => 4 then your answer would be 2

1 Comment

yes thank you for the advise, you are write, I kind of misunderstood the way how the for loop was actually calculating.

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.