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

loop

 
mohamed hamdy
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what will be the output when compiling and running this code?

the answer is "fail to compile", it made sense for me since the condition in the for loop will be false from the begining and that makes the block of the for loop unreachable, but when i compiled and run the code it gives "o" as output.
can somone emphaisis that?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even though we know that i will be greater than 0 at the start of the loop and, hence, the loop will never execute, the compiler doesn't know that. It sees a conditional test on a variable and thinks "hmmm...it could pass, so I'll let it be." Therefore, you do not get an "unreachable statement" error when compiling this. If you change the loop to this:

You will get an "unreachable statement" error when you try to compile. In this case, the compiler knows that the loop can never execute and issues an error message to you.
I hope that helps,
Corey
 
param kiran
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the "for (int i=10; i<0; i++)" statement, the condition i<0 is false so the for loop is never executed.
The System.out.println(counter); statement is outside of the for loop if you observe closely.
Since the counter is initialized to 0 the print statement prints this out.
 
mohamed hamdy
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Corey , thanks Param
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic