How to Calculate the Sum of an Array of Numbers in Batch Script
Processing lists of numeric data, such as totaling a list of file sizes, summing up server response times, or calculating a final score from individual metrics, is a fundamental part of data processing. In Batch, you can iterate through an array of variables and use the set /a command to accumulate a running total.
In this guide, we will demonstrate how to sum an array of numbers using a simple loop.
The Strategy: The Accumulator
To sum an array:
- Initialize a
totalvariable to 0. - Iterate through the array elements using a
FOR /Lloop. - For each element, add it to the
totalusingset /a. - Display the result.
The set /a command performs signed 32-bit integer arithmetic. The maximum result it can hold is 2,147,483,647. If your sum may exceed this, use the PowerShell bridge shown in the Best Practices section.
Implementation Script
@echo off
setlocal enabledelayedexpansion
:: 1. Define the Array (Numbers to sum)
set "size=5"
set "ARR_1=150"
set "ARR_2=25"
set "ARR_3=75"
set "ARR_4=10"
set "ARR_5=50"
:: 2. Verify the array is not empty
if not defined ARR_1 (
echo [ERROR] Array is empty - nothing to sum.
pause
exit /b 1
)
set "total=0"
echo Array elements: !ARR_1! !ARR_2! !ARR_3! !ARR_4! !ARR_5!
:: 3. Accumulation Loop
for /L %%i in (1,1,%size%) do (
:: Use call to resolve the dynamic variable name
call set "val=%%ARR_%%i%%"
set /a "total+=val"
)
echo.
echo ==========================================
echo TOTAL SUM: !total!
echo ==========================================
endlocal
pause
Why Sum an Array in Batch?
- Quota Auditing: If your script lists the space used by multiple folders into variables, you can sum them to get the total consumption across all targets.
- Health Checks: Totaling the number of "Warnings" across several log files to determine if a system-wide alert should be triggered.
- Process Monitoring: Summing the durations of multiple script stages to report the total execution time to an administrator.
Important Limitations
Batch uses 32-bit signed integers. The maximum value for total is 2,147,483,647. If your sum exceeds this, the number will silently overflow and wrap to a large negative number. Batch provides no warning when this occurs, so always verify your data range before relying on the result.
- 32-Bit Integer Limit: Batch uses 32-bit signed integers. This means the maximum value for
totalis 2,147,483,647. If your sum exceeds this, the number will "overflow" (effectively becoming a large negative number). - No Decimals: Batch only understands whole numbers.
12.5will result in a syntax error or a truncated value of12. - Variable Names: Ensure your array indexing is consistent (e.g.,
ARR_1,ARR_2). If the loop tries to access a missing index, the math will fail.
Best Practices
- Clear Variables: If you are performing multiple sums, always reset your
totalto 0 before starting a new loop. - Verify Arithmetic: Since Batch math is silent on overflows, double-check your data volume. If you expect gigabytes but your sum is negative, you've hit the 32-bit ceiling.
- PowerShell for Large Numbers: If you need to sum numbers larger than 2.1 billion or need decimal precision, use a PowerShell one-liner:
powershell -NoProfile -Command "(150, 25, 75, 10, 50 | Measure-Object -Sum).Sum"
To calculate the average alongside the sum, add a set /a "average=total / size" line after the loop completes. Note that this produces an integer result (truncated, not rounded) due to Batch's integer-only arithmetic.
Conclusion
Calculating the sum of an array is a basic but essential mathematical operation for any analysis script. By utilizing the set /a command within a structured loop, you can turn a collection of individual metrics into a high-level summary. This ability to aggregate data ensures your Batch scripts provide clear, actionable totals for system reporting and auditing.