The Loop statements are used to execute a particular statements a pre-defined number of times. This statement allows a particular piece of code to be repeatedly executed. The Loop statement is enclosed in a LOOP and the END LOOP keywords, and is classified as an iteration statement. The Java script, like many other programming languages, supports the use of Loops.
Many different types of loop statements are available, such as:
- While Loop
- For Loop
- Do-while Loop
The For Loop is a commonly used loop statement. This loop is associated with a loop counter or a loop variable, which allows the body of the For loop to know the exact sequence of each iteration. The body of the For loop is the code that is being executed repeatedly. These loops are generally used when the programmer knows the number of iterations before executing the program. Not only this, the keyword For, which constitutes the name of the For loop originates from the English language word For.
When the Java script executor finds a For loop in a program, it first executes or runs the initialization statements, initializing all the variables, and then it executes and checks for the given conditions. The interpreter enters the ‘loop’ once the condition evaluates to True. The condition is executed repeatedly till the condition evaluates to false. This case also makes the end of the loop.
When running a loop in Java, you must consider the following points:
- When the Java interpreter evaluates a For loop, it initializes all the variables.
- The condition is evaluated only after the initialization statements are executed.
- The update statements are executed and the conditions are checked after every iteration.
The program code given below executes a For loop to prints the digits from 11 to 20.
var message_variable = “”;
for (var Counter_variable = 11; Counter_variable <= 20; Counter_variable ++)
{
message_variable = message_variable + Counter_variable + “\n”;
}