• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

doubt

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i came across this question in JQ++. it is as follows:
public class Test
{
public static void main(String[] args)
{
int sum=0;
for(int i=0,j=10;sum>20;++i,--j)
{
sum +=i+j;
}
System.out.println(sum);
}
}
i thought the answer would be 20 but instead when i saw the answer it was 0.could anyone please explain this .
Thanks
Lakshmi
 
High Plains Drifter
Posts: 7289
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The for loop never executes because the test condition (sum > 20) fails on the first pass.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
 
lp
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks i got it .
 
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are getting 0 as the output because the condition sum>20 is false & the program jumps out of the for loop printing sum as 0.
Change the condition to sum<=20.<br />

Originally posted by lakshmi panda:<br /> i came across this question in JQ++. it is as follows:<br /> public class Test <br /> {<br /> public static void main(String[] args)<br /> {<br /> int sum=0;<br /> for(int i=0,j=10;sum>20;++i,--j)
{
sum +=i+j;
}
System.out.println(sum);
}
}
i thought the answer would be 20 but instead when i saw the answer it was 0.could anyone please explain this .
Thanks
Lakshmi


 
reply
    Bookmark Topic Watch Topic
  • New Topic