Question

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

Was it helpful?

Solution 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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top