0

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%
asked Dec 12, 2013 at 3:25

2 Answers 2

4

There are several correct ways to do this and one wrong way. The bad way is this:

for /l %%x in (110, -2, 100) do (
 set /a totalCount = %totalCount% + %%x
)

Because %totalCount% is expanded just once, before the for is executed, so the value of the sum is always 0 plus each term.

One possible solution is use Delayed Expansion as Dale suggested:

echo off
setlocal enabledelayedexpansion
set /a totalCount = 0
for /l %%x in (110, -2, 100) do (
 set /a totalCount = !totalCount! + %%x
)
echo total is %totalCount%

This way, the value of !totalCount! is correctly replaced in each for cycle. However, this is not needed either, because set /A command takes the current value of the variables by itself each time it is executed:

echo off
set /a totalCount = 0
for /l %%x in (110, -2, 100) do (
 set /a totalCount = totalCount + %%x
)
echo total is %totalCount%

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:

echo off
set /a totalCount = 0
for /l %%x in (110, -2, 100) do (
 set /a totalCount += %%x
)
echo total is %totalCount%
answered Dec 12, 2013 at 4:44
Sign up to request clarification or add additional context in comments.

Comments

1

Try changing %totalCount% to !totalCount!. Therefore, the code should look like this:

echo off
setlocal enabledelayedexpansion
set /a totalCount = 0
for /l %%x in (110, -2, 100) do (
 set /a totalCount = !totalCount! + %%x
)
echo total is !totalCount!
answered Dec 12, 2013 at 3:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.