how many loops is this running? – java coding

This loop have condition to run when i is not equal 10. Because i starts at 1 and increases by 2 on every iteration, i will be always odd number and therefore can newer equal 10. So condition for loop will be always true. Simply put: your loop will go indefinitely.

About for statement from

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the “for loop” because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination; increment) {
    statement(s)
}
  • The initialization expression initializes the loop; it’s executed once, as the loop begins.
  • The termination expression is invoked before each iteration. When it evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

More info about for statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

//edit
Correct code for 5 loops if you have to use ‘!=’ comparison would be:

for(int i = 1; i != 11; i += 2)
// i==1 PASS
// i==3 PASS
// i==5 PASS
// i==7 PASS
// i==9 PASS
// i==11 FAILED, Loop ends here

although it’s better to use

for(int i = 1; i < 10; i += 2)
//or
for(int i = 1; i < 11; i += 2)

this way, your loop will end after 5 loops and safer for many reasons

Leave a Comment