0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Find Average of Array Elements

Use a Bash script that sums array elements with a loop and divides by the number of elements, like: sum=0; for i in "${arr[@]}"; do ((sum+=i)); done; avg=$((sum/${#arr[@]})).
📋

Examples

Inputarr=(10 20 30)
OutputAverage: 20
Inputarr=(5 15 25 35)
OutputAverage: 20
Inputarr=(7)
OutputAverage: 7
🧠

How to Think About It

To find the average, add all numbers in the array together, then divide that total by how many numbers there are. This means looping through each element to sum them, then using the count of elements for division.
📐

Algorithm

1
Initialize a sum variable to zero.
2
Loop through each element in the array and add it to sum.
3
Count the number of elements in the array.
4
Divide the sum by the count to get the average.
5
Print the average.
💻

Code

bash
arr=(10 20 30 40 50)
sum=0
for i in "${arr[@]}"; do
  ((sum+=i))
done
count=${#arr[@]}
avg=$((sum / count))
echo "Average: $avg"
Output
Average: 30
🔍

Dry Run

Let's trace the array (10 20 30 40 50) through the code

1

Initialize sum

sum=0

2

Add elements

sum=10 after first element, sum=30 after second, sum=60 after third, sum=100 after fourth, sum=150 after fifth

3

Count elements

count=5

4

Calculate average

avg=150 / 5 = 30

IterationElementSum
11010
22030
33060
440100
550150
💡

Why This Works

Step 1: Sum all elements

The loop uses for to add each array element to sum, accumulating the total.

Step 2: Count elements

The expression ${#arr[@]} gets the number of elements to know how many to divide by.

Step 3: Calculate average

Dividing the total sum by the count gives the average value of the array elements.

🔄

Alternative Approaches

Using awk for floating point average
bash
arr=(10 20 30 40 50)
echo "${arr[@]}" | awk '{sum=0; for(i=1;i<=NF;i++) sum+=$i; print "Average:", sum/NF}'
This method supports decimal averages but requires awk installed.
Using bc for precise division
bash
arr=(10 20 30 40 50)
sum=0
for i in "${arr[@]}"; do ((sum+=i)); done
count=${#arr[@]}
avg=$(echo "scale=2; $sum / $count" | bc)
echo "Average: $avg"
This method allows decimal places using bc but adds complexity.

Complexity: O(n) time, O(1) space

Time Complexity

The script loops once through all n elements to sum them, so time grows linearly with array size.

Space Complexity

Only a few variables are used regardless of array size, so space is constant.

Which Approach is Fastest?

The direct Bash loop is fastest for integer sums; using awk or bc adds overhead but supports decimals.

ApproachTimeSpaceBest For
Bash loop with integer divisionO(n)O(1)Simple integer averages, fastest
awk one-linerO(n)O(1)Floating point averages, easy one-liner
Bash with bc for decimalsO(n)O(1)Precise decimal averages, slightly slower
💡
Use ${#arr[@]} to get the number of elements in a Bash array.
⚠️
Forgetting to quote array expansions like "${arr[@]}" can cause word splitting errors.