Loop Variable

🙋 Need help? Ask an expert now!

Now that we are working with loops, let's explore "loop control variables". Loop control variables are ordinary int variables that are used to dictate elements such as how many times a loop will execute. Not all loops will necessarily have loop control variables, but it is important to recognize if one is present. Look at the program below to see what a "loop control variable" is.

LoopVariableExample.java
package exlcode;

public class LoopVariableExample {

  public static int exampleVariableOne = 10;
  public static int counterOne = 0;

  public static void main(String[] args) {
    System.out.println("Counting forward from 0-10:");
    // counterOne is the loop variable
    while (exampleVariableOne >= counterOne) {
      System.out.print(counterOne + " ");
      counterOne++;
    }
    System.out.println("\nCounting backward from 0-10:");
    //  "counterTwo" is the loop variable
    for (int counterTwo = exampleVariableOne; counterTwo >= 0; counterTwo--) {
      System.out.print(counterTwo + " ");
    }
    // The following statement will cause a runtime error:
    // System.out.println(counterTwo);
  }
}

counterOne and counterTwo are both loop control variables that control when the loop will terminate as well as the number of times the loop will execute before it terminates. In both examples above, the loop control value is incremented or decremented by a certain value every time the loop is executed. This step is required in the program because the loop will run forever if the condition always evaluates true.

Let's think back to Access Control and remember to consider the scope of the variables inside the loop. Any variable declared inside the for or while loop or inside the parenthesis of a for statement can only be used in the body of the loop. They cannot be printed or accessed in any way after the loop is terminated. If you look at the code above, there is a print statement in comments. If you uncomment the statement and run the program, it will cause an error because counterTwo cannot be referenced outside the for loop.

Application Question

Consider the following code segments:

I.

int varOne = 1;
            while (varOne < 20){
              if (varOne % 3 == 1){
                System.out.print(varOne + " ");
              }
              varOne = varOne + 3;    
            }
            
            

II.

for (int varOne = 1; varOne < 20; varOne++)
            {
              if (varOne % 3 == 1){
                System.out.print(varOne + " ");
              }
            }
            
            

III.

for (int varOne = 1; varOne < 20; varOne = varOne + 3)
            {
              System.out.print(varOne + " ");
            }
            

Which of the code segments above will produce the following output? 1 4 7 10 13 16 19