• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question from jqplus

 
K2Joshi
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I have the following code , i have no clue why i am getting the out put as 3,3. Please help me.
public class Operator
{
public static void main(String args[ ] )
{
int k = 0;
int m = 0;
for ( int i = 0; i <= 3; i++)
{
k++;
if ( i == 2)
{
i=10; // line 1
}
m++;
}
System.out.println( k + " , " + m );
}
}

Thanks in advance
Ketu
 
srikrish
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
k2,
During the loop, when i becomes 2, k gets incremented from 2 to 3. Then i gets set to 10 (by line 1). But the for loop is still on and it does not check for the value of i until the current iteration is completed. And the iteration for i's value of 2 is not completed until m is incremented to 3. After this, i is incremented to 11 (by the for loop) and then its value is checked. Since this is greater than 3, the control goes gets out of the for loop and goes to the println statement. Since the current values of k and m are 3, you get 3,3 as the o/p.
Hope this helps.
[This message has been edited by srikrish (edited September 13, 2000).]
 
K2Joshi
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot srikrish,
Ketu
 
weisheZhao
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if u try to compile and run this code, u will see the clue of the running.
public class Operator
{
public static void main(String args[ ] ) {
int k = 0;
int m = 0;
for ( int i = 0; i <= 3; i++) {
k++;
if ( i == 2) {
i=10; // line 1
}
m++;
System.out.println("k=" +k + " , " +" m=" +m +", i=" +i);
}
System.out.println( k + " , " + m );
}
}
output:
k=1 , m=1, i=0
k=2 , m=2, i=1
k=3 , m=3, i=10
3 , 3
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic