Print an array elements based on an input param
Posted: 23 May 2021 13:51
Is there a way to print an array elements based on an input param, let's say 100, all in one line.
To simplify the question, I have the following batch file and it will print 3 elements in one line.
@echo off
setlocal enabledelayedexpansion
set w[0]=1
set w[1]=2
set w[2]=3
set w[3]=4
set w[4]=5
call :printArray 3
exit /b
:printArray %1
if %1 equ 1 echo !w[0]!
if %1 equ 2 echo !w[0]! !w[1]!
if %1 equ 3 echo !w[0]! !w[1]! !w[2]!
if %1 equ 4 echo !w[0]! !w[1]! !w[2]! !w[3]!
if %1 equ 5 echo !w[0]! !w[1]! !w[2]! !w[3]! !w[4]!
What if I have a bigger array and I want to print up to 100 elements?
I could modify the :printArray function to do like the above but it really tedious and time consuming.
Is there anyway to make it auto generate the number of elements that I would like to print based on input number?
To simplify the question, I have the following batch file and it will print 3 elements in one line.
@echo off
setlocal enabledelayedexpansion
set w[0]=1
set w[1]=2
set w[2]=3
set w[3]=4
set w[4]=5
call :printArray 3
exit /b
:printArray %1
if %1 equ 1 echo !w[0]!
if %1 equ 2 echo !w[0]! !w[1]!
if %1 equ 3 echo !w[0]! !w[1]! !w[2]!
if %1 equ 4 echo !w[0]! !w[1]! !w[2]! !w[3]!
if %1 equ 5 echo !w[0]! !w[1]! !w[2]! !w[3]! !w[4]!
What if I have a bigger array and I want to print up to 100 elements?
I could modify the :printArray function to do like the above but it really tedious and time consuming.
Is there anyway to make it auto generate the number of elements that I would like to print based on input number?