I am doing some batch practice and I am trying to do a loop to go backwards and count the numbers from 110 to 100, but only the even numbers. I almost got it to work, but for some reason totalCount is not updating every time the for loop goes around. At the end it prints the total as 100
which is simply the last number of the loop. What am I doing wrong?
::echo off
setlocal enableextensions
setlocal enabledelayedexpansion
set /a totalCount = 0
for /l %%x in (110, -2, 100) do (
set /a totalCount = %totalCount% + %%x
)
echo total is %totalCount%
Try changing
%totalCount%
to!totalCount!
. Therefore, the code should look like this:There are several correct ways to do this and one wrong way. The bad way is this:
Because
%totalCount%
is expanded just once, before thefor
is executed, so the value of the sum is always 0 plus each term.One possible solution is use Delayed Expansion as Dale suggested:
This way, the value of
!totalCount!
is correctly replaced in eachfor
cycle. However, this is not needed either, becauseset /A
command takes the current value of the variables by itself each time it is executed:Moreover,
set /A
command have a way to increment a variable that don't even requires to write its name, so the matter of this discussion completely dissapear: