How to Calculate the Average of an Array of Numbers in Batch Script
Calculating the Average (Mean) of a data set is a standard way to determine "Typical" performance or usage. In Batch, this requires a two-step process: first, calculating the total sum of all elements in your array, and second, dividing that sum by the number of elements. While Batch math is limited to whole numbers, it is excellent for quick, integer-based averages.
In this guide, we will demonstrate how to calculate the average of an array using an accumulator and a counter.
The Strategy: Sum / Count
- Initialize a
totalvariable to 0. - Iterate through the array, adding each item to
total. - Store the number of items (
count). - Perform the division:
set /a "avg=total / count".
Batch arithmetic performs integer division, which truncates (rounds toward zero) rather than rounding to the nearest whole number. For example, 85 / 2 produces 42, not 43. If you need decimal precision, use the PowerShell alternative shown at the end of this guide.
Implementation Script
@echo off
setlocal enabledelayedexpansion
:: 1. Define the Array (Sample Scores)
set "size=5"
set "ARR_1=80"
set "ARR_2=95"
set "ARR_3=70"
set "ARR_4=100"
set "ARR_5=85"
:: 2. Verify the array is not empty
if not defined ARR_1 (
echo [ERROR] Array is empty - nothing to average.
pause
exit /b 1
)
set "total=0"
echo Calculating average for: !ARR_1! !ARR_2! !ARR_3! !ARR_4! !ARR_5!
:: 3. Sum the elements
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"
)
:: 4. Calculate Average (Sum / Size)
if !size! GTR 0 (
set /a "avg=total / size"
) else (
echo [ERROR] Cannot divide by zero - size is 0.
pause
exit /b 1
)
echo.
echo ==========================================
echo TOTAL SUM: !total!
echo COUNT: !size!
echo AVERAGE: !avg!
echo ==========================================
endlocal
pause
Why Calculate Averages?
- Usage Baselines: Finding the average length of a script's execution over a week to identify "Unusually slow" future runs.
- Health Auditing: Calculating the average number of files generated per day to predict storage growth.
- Benchmarking: Comparing the average performance of several different servers to determine which one is most efficient.
Important Limitations
Batch uses 32-bit signed integers. The sum must not exceed 2,147,483,647 before division occurs. If your total overflows, the division will be performed on an incorrect wrapped value. Batch provides no warning when this happens.
- Integer Math (No Decimals): Batch arithmetic does not support floating point numbers.
85 / 2will result in42, not42.5. The decimal part is simply truncated (thrown away). - 32-Bit Limit: The Sum must not exceed 2.1 billion. If your total is very high, the division will be performed on an incorrect, overflowed sum.
- Division by Zero: Always verify that your
sizeis greater than 0 before performing the division, or the script will crash with a "Division by zero" error.
Better Precision (PowerShell Alternative)
If you need accurate decimals (e.g., an average of 42.5), use a PowerShell bridge from within your Batch file:
@echo off
powershell -NoProfile -Command "(80, 95, 70, 100, 85 | Measure-Object -Average).Average"
pause
To display the remainder alongside the integer average, add set /a "remainder=total %% size" after the division. This tells you how much precision was lost to truncation (e.g., a remainder of 0 means the average was exact).
Conclusion
Calculating an average transforms raw individual numbers into a single, understandable metric of performance. By combining a summation loop with whole-number division, you can quickly baseline your system data and identify outliers. This ability to interpret mathematical trends is essential for building scripts that effectively monitor health and project future resource requirements.