How can I write windows batch file command with loop and % operator?

5

I want to write the following code in a batch file. How can I do that?

for (i=0; i<100; i++)
{
   rem = i % 10;
   if(rem == 0)
   {
     // ECHO something
   }
   else
   {
     ECHO i         
   }
}

Bobs

Posted 2017-06-10T09:18:07.760

Reputation: 2 635

Answers

11

It's rather complicated, because of the way variable expansion in loops works in batch files. Batch files do have their own for construct; no need to mess around with gotos. %% is the modulo operator in batch files, as % is reserved for expansion of variables.

This code works for me:

@echo off
setlocal enabledelayedexpansion
for /l %%i in (0,1,99) do (
  set /a remainder = %%i %% 10
  if !remainder! == 0 (
    echo something
  ) else (
    echo %%i
  )
)
endlocal

Glorfindel

Posted 2017-06-10T09:18:07.760

Reputation: 2 942

1Nitpicking i<100 means max 99 so it should be for /l %%i in (0,1,99) do ( – LotPings – 2017-06-10T16:33:15.183

The for loop can be comblned with a Call to a subroutine to avoid the delayed Expansion difficulties – miracle173 – 2017-06-10T17:44:01.490

2

Modulo can be done with set /a. Loops can be done with goto, just like how you convert those for loops into goto in C

@echo off
set "i=0"
:loop
if %i% equ 100 goto :endfor
set /a "mod=i %% 10"
if %mod% equ 0 (
    echo something %mod%
) else (
    echo %i%
)
set /a "i+=1"
goto :loop
:endfor

Notice that rem is a command for starting a comment so using rem in the script may result in undesired behavior

The loop can be made simpler with for /l but now you have to enable delayed expansion because the whole body of for is parsed at once

phuclv

Posted 2017-06-10T09:18:07.760

Reputation: 14 930

The for loop can be comblned with a Call to a subroutine to avoid the delayed Expansion difficulties – miracle173 – 2017-06-10T17:44:13.257