While Statement Implementation



There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels.

The following diagram shows the diagrammatic explanation of this loop.

While Statement Implementation

The first part of the while implementation is to set the counters which will be used to control the evaluation of the ‘if’ condition. We then define our label which will be used to embody the entire code for the while loop implementation. The ‘if’ condition evaluates an expression. If the expression evaluates to true, the code block is executed. If the condition evaluates to false then the loop is exited. When the code block is executed, it will return back to the label statement for execution again.

Following is the syntax of the general implementation of the while statement.

Syntax

Set counters
:label
If (expression) (
   Do_something
   Increment counter
   Go back to :label
)
  • The entire code for the while implementation is placed inside of a label.

  • The counter variables must be set or initialized before the while loop implementation starts.

  • The expression for the while condition is done using the ‘if’ statement. If the expression evaluates to true then the relevant code inside the ‘if’ loop is executed.

  • A counter needs to be properly incremented inside of ‘if’ statement so that the while implementation can terminate at some point in time.

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

Following is an example of a while loop statement.

Example

@echo off
SET /A "index = 1"
SET /A "count = 5"
:while
if %index% leq %count% (
   echo The value of index is %index%
   SET /A "index = index + 1"
   goto :while
)

In the above example, we are first initializing the value of an index integer variable to 1. Then our condition in the ‘if’ loop is that we are evaluating the condition of the expression to be that index should it be less than the value of the count variable. Till the value of index is less than 5, we will print the value of index and then increment the value of index.

Output

The above command produces the following output.

The value of index is 1
The value of index is 2
The value of index is 3
The value of index is 4
The value of index is 5
batch_script_return_code.htm
Advertisements