I have to write a program that lets the user enter in as many numbers as he wants and determine which is the largest, smallest, what the sum is, and the average of all the numbers entered. Am I forced to use arrays to do this or is there another way? If I have to use an array, can someone help me out with an example of how I should be approaching this question? Thanks
2 Answers
You do not need an array. Just keep the largest and smallest number so far, the count of numbers and the sum. The average is simply sum/count
.
To read the input, you can use read
in a while
loop.

- 231,213
- 25
- 204
- 289
Simple straight forward attempt, with some issues:
#!/bin/bash
echo "Enter some numbers separated by spaces"
read numbers
# Initialise min and max with first number in sequence
for i in $numbers; do
min=$i
max=$i
break
done
total=0
count=0
for i in $numbers; do
total=$((total+i))
count=$((count+1))
if test $i -lt $min; then min=$i; fi
if test $i -gt $max; then max=$i; fi
done
echo "Total: $total"
echo "Avg: $((total/count))"
echo "Min: $min"
echo "Max: $max"
Also tested with /bin/sh, so you don't actually need bash, which is a much larger shell. Also note that this only works with integers, and average is truncated (not rounded).
For floating point, you could use bc. But instead of dropping into a different interpreter multiple times, why not just write it in something a bit more suitable to the problem, such as python or perl, eg in python:
import sys
from functools import partial
sum = partial(reduce, lambda x, y: x+y)
avg = lambda l: sum(l)/len(l)
numbers = sys.stdin.readline()
numbers = [float(x) for x in numbers.split()]
print "Sum: " + str(sum(numbers))
print "Avg: " + str(avg(numbers))
print "Min: " + str(min(numbers))
print "Max: " + str(max(numbers))
You could embed it in bash using a here document, see this question: How to pipe a here-document through a command and capture the result into a variable?
-
-
sorry, my rep is too low for voting just yet. Thanks again though, when I can vote up i will def come back! – Drubs1181 Apr 26 '15 at 17:33