# Shell program to find average of n numbers

Let's write a shell program to find average of n numbers

## Algorithm

1. Get N (Total Numbers)

2. Get N numbers using loop

3. Calculate sum

4. Average = sum / N

5. print the result.

## Average of n numbers - Shell Script

```#shell script to find average of n numbers

echo "Enter Size(N)"

i=1
sum=0

echo "Enter Numbers"
while [ \$i -le \$N ]
do
sum=\$((sum + num))     #sum+=num
i=\$((i + 1))
done

avg=\$(echo \$sum / \$N | bc -l)

echo \$avg
```

We can't directly perform floating point arithmetic in bash.

So that we have used bc "An arbitrary precision calculator language" to calculate the avg.

## Output

Enter Size(N)

5

Enter Numbers

10

20

30

40

50

30.00000000000000000000

Enter Size(N)

3

Enter Numbers

1

2

5

2.66666666666666666666

## Use printf to print required floating points

```#shell script to find average of n numbers

echo "Enter Size(N)"

i=1
sum=0

echo "Enter Numbers"
while [ \$i -le \$N ]
do
sum=\$((sum + num))     #sum+=num
i=\$((i + 1))
done

avg=\$(echo \$sum / \$N | bc -l)

printf '%0.2f' "\$avg"
```

%0.2f will print only 2 floating numbers.

Enter Size(N)

5

Enter Numbers

10

20

30

40

50

30.00

Enter Size(N)

3

Enter Numbers

1

2

5

2.67