The syntax of the general implementation of the while statement is given below:
set counters
:label
if (expression) (
do_something...
increment counter
go back to :label
)Explanation:
- The entire while implementation code is placed inside a label.
- The counter variables must be set or initialized before starting the while loop implementation.
- The expression for the while condition is executed with the
ifstatement. If the expression is true, the corresponding code within theifloop is executed. - A counter must be incremented correctly within the
ifstatement 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 the
ifstatement again.
Example
Example of a while loop in which the variable index is initialized to 1 and incremented with each execution of the while loop until index is less than or equal to the count variable (initialized to 5):
@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
)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