This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question from jqplus Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question from jqplus" Watch "Question from jqplus" New topic
Author

Question from jqplus

K2Joshi
Greenhorn

Joined: Aug 23, 2000
Posts: 17
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

Joined: Sep 12, 2000
Posts: 63
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

Joined: Aug 23, 2000
Posts: 17
Thanks a lot srikrish,
Ketu
weisheZhao
Greenhorn

Joined: Sep 10, 2000
Posts: 18
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question from jqplus
 
Similar Threads
charAt problem....
Increment Test
deal with loops.....
why??
what is the Output? and why?