0

I am writing a for loop in a batch file, which is to do arithmetic to a variable each iteration. The loop looks like this:

@echo off
setlocal enabledelayedexpansion
SET d=10
echo !d!

for /L %%t IN (0,1,9) DO (
    SET /A d = %d% + 10
    echo !d!
)

The arithmetic only is good for the first iteration. 'd' is to start at 10 and add by ten each time (10 20 30 ...) but it always stops at 20. In the output of the command prompt it will show:

10
20
20
...
20
20

How can I write this so it will add by ten for the entire loop?

2 Answers 2

3

You're close, but you missed using delayed expansion in one spot.

Change SET /A d = %d% + 10 to SET /A d = !d! + 10

@echo off
setlocal enabledelayedexpansion
SET d=10
echo !d!

for /L %%t IN (0,1,9) DO (
    SET /A d = !d! + 10
    echo !d!
)
Sign up to request clarification or add additional context in comments.

1 Comment

Or set /A "d+=10" or set /A d = d +10
1

Do as @JosefZ says if you need the academic exercise of arithmetic in a loop. If you want to get the same result with less code you can do this.

for /L %%t IN (20,10,110) DO echo %%t

1 Comment

Thanks! I can get away with doing a loop but as you said, i need it done this way for the academic exercise. Also, the variable 'd' is used in a nested loop else where and has to continue on from where it left off

Your Answer

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.