How do I modify the function so as to echo in the following sequence,
1st,2nd,4th,5th,7th,8th,10th,11th element and so on....
What you are trying to do is print every element that is not a multiple of 3. The easiest way to do this is with a modulo operation.
Psuedocode:
if %%n modulo 3 >= 1 then print something.
The modulus operator in batch file arithmetic using set /a
is %%
.
Example batch file (test.cmd):
@echo off
setlocal enabledelayedexpansion
for /l %%n in (1 1 20) do (
rem print values where cnt is not a multiple of 3
set /a _mod=%%n %% 3
if [!_mod!] GEQ [1] (
echo %%n
)
)
endlocal
Output:
F:\test>test
1
2
4
5
7
8
10
11
13
14
16
17
19
20
You can use the same technique in your batch file.
Snippet:
@echo off
setlocal enabledelayedexpansion
rem collect data and insert into array
rem ...
rem print values where cnt is not a multiple of 3
for /l %%n in (1 1 !cnt!) do (
set /a _mod=%%n %% 3
if [!_mod!] GEQ [1] (
echo !output[%%n]!
)
)
endlocal
More general solution
This is how I would have done it in C programming
for(n=1;i<cnt;n+=3){printf("%d %d",output[n],output[n+1])}
Example batch file (test.cmd):
@echo off
setlocal enabledelayedexpansion
for /l %%n in (%1 3 20) do (
set /a _next=%%n+1
echo %%n !_next!
)
)
endlocal
Notes:
- Pass the starting value as an argument to the batch file.
- Modify as necessary to output your array values.
Usage:
F:\test>test 1
1 2
4 5
7 8
10 11
13 14
16 17
19 20
F:\test>test 2
2 3
5 6
8 9
11 12
14 15
17 18
20 21
An even more general solution
But I said in the comments I want to output 2,3,6,7,10,11,14,15,18...
Note that your c
solution will not handle this case, even if you change the loop starting value ...
You need to have two variable parameters to the for
loop, one for the start value, and one for the increment.
Example batch file (test.cmd):
@echo off
setlocal enabledelayedexpansion
for /l %%n in (%1 %2 20) do (
set /a _next=%%n+1
echo %%n !_next!
)
)
endlocal
Usage:
F:\test>test 2 4
2 3
6 7
10 11
14 15
18 19
Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- for /l - Conditionally perform a command for a range of numbers.
- if - Conditionally perform a command.
- set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.