Tips on for Loops

  1. Remember that if you need to execute more than one statement inside a for loop that you must enclose the statements in curly braces, making them a compound statement, or block of code.
  2. Don't forget the semi-colons inside the for statement, and don't put one before the close parenthesis:

  3. Don't put a semi-colon after the close parenthesis. 
    for (i =1; i <= 10; i++);
        System.out.println("i is: + i);
    

    This code will execute the for loop and do nothing each time through. This is because the extra semicolon at the end is an empty statement, which does nothing. Then after loop is finished, the code will print

    i is 11
    

    The correct way to indent the code so it accuratly shows the execution would be:

    for (i =1; i <= 10; i++)
        ;  // this is the empty statement
    System.out.println("i is: + i);
    
  4. Write your logical expressions so that they do not check for equality or inequality because it is easy to make a mistake that results in an loop that never ends. This is called an infinite loop.

    An Example Infinite Loop

    for (i = 1; i != 30; i = i + 5)
        System.out.println("i is: + i);
    
    Draw it and you will see. A much safer way to write the loop would be to use <=, as shown in Figure 7-7.

    Not an Infinite Loop

    for (i = 1; i <= 30; i = i + 5)
        System.out.println("i is: + i);
    
    Although it is still probably wrong (it prints 1, then 6, then 11, ...) it is not infinite, like the previous example.

  5. A for loop can execute the code within it 0 times. Let's say that the user enters 0 when prompted for the number of times to do something. Your program stores it in an object named numTimes, and has the following for loop:
    for (i = 1; i <= numTimes; i++)
        System.out.println("i is: + i);
    
    Since the logical expression i <= numTimes ends up being 1 <= 0, and that evaluates false, the code inside the loop is never executed.

There are other types of for loops that we will learn later, but remember that the classic for loop is used for counting. Sometimes, however you will want to execute code over again, but not execute it a certain number of times. This means that you will not use a counting loop. A while loop is used for this type of execution.