Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Loop Variable
Introduction To Java Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Introduction To Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.