Classic for Loop Implementation


Following is the classic ‘for’ statement which is available in most programming languages.


for(variable declaration;expression;Increment) {
   statement #1
   statement #2

The Batch Script language does not have a direct ‘for’ statement which is similar to the above syntax, but one can still do an implementation of the classic ‘for’ loop statement using if statements and labels.

Following is the general flow of the classic ‘for’ loop statement.

Classic for Loop Implementation

Let’s look at the general syntax implementation of the classic for loop in batch scripting.

Set counter

If (expression) exit loop
Increment counter
Go back to :label
  • The entire code for the ‘for’ implementation is placed inside of a label.

  • The counters variables must be set or initialized before the ‘for’ loop implementation starts.

  • The expression for the ‘for’ loop is done using the ‘if’ statement. If the expression evaluates to be true then an exit is executed to come out of the loop.

  • A counter needs to be properly incremented inside of the ‘if’ statement so that the ‘for’ implementation can continue if the expression evaluation is false.

  • Finally, we will go back to our label so that we can evaluate our ‘if’ statement again.

Following is an example of how to carry out the implementation of the classic ‘for’ loop statement.


@echo off 
SET /A i = 1 

IF %i%==5 GOTO END 
echo The value of i is %i% 
SET /a i=%i%+1 


The above command produces the following output.

The value of i is 1 
The value of i is 2 
The value of i is 3 
The value of i is 4