Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

For loop / variable ?

 
Willie Toma
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the following code print only "Total 0"?
public class Calc {
public static void main (String args []) {
int total = 0;
for (int i = 0, j = 10; total > 30; ++i, --j) {
System.out.println(" i = " + i + " : j = " + j);
total += (i + j);
}
System.out.println("Total " + total);
}
}
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Willie
In your for loop the condition is set to be total > 30, meaning that as long as total is greater than 30 it will run. Since total starts out as 0 it is never greater than 30 so your loop never executes and so total stays at 0. If you make it 'total < 30' then it will run until total is greater than 30 and you'll get something other than 0.

hope that helps
Dave
 
Willie Toma
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic