java – doubt in for loop – Education Career Blog

i have the following code

public static void main(String args) {
  int x=0;
  int y=0;
  for(int z=0;z<5;z++)
    if((++x>2)||(++y>2))
      x++;

  System.out.println(x+" "+y);

}

For this the output is 8 2

public static void main(String args) {
  // TODO Auto-generated method stub
  int x=0;
  int y=0;
  for(int z=0;z<5;z++){
    if((++x>2)||(++y>2))
      x++;

    System.out.println(x+" "+y);
  } 
}

i can understand the second code that it prints everytime till the loop completes.
For the first code
when x becomes 3 in the if loop value will be incremented to 4 and after that what well happen will it go to sop or to for loop to complete the loop?

,

i editet you entry because you missed to mak your code as such… after reading the question, i think you should see the answer yourself if you look at how it’s indented.

for the future: use curly braces every time, not just if there is more than one line in the block, otherwise you will only get confused.

,

The for loop is controlled by the value of z, the value of x has no bearing on when the loop stops.

Leave a Comment