In: Computer Science
# Total numbers
n=7
# copying the value of n
m=$n
# initialized sum by 0
sum=0
# array initialized with
# some numbers
array=(3 4 1 8 9 10 2)
#sorted array for median
sortedarray=( $( printf "%s\n" "${array[@]}" | sort -n ) )
# loop until n is greater
# than 0
while [ $n -gt 0 ]
do
# copy element in a
# temp variable
num=${sortedarray[`expr $n - 1`]}
# add them to sum
sum=`expr $sum + $num`
# decrement count of n
n=`expr $n - 1`
done
# displaying the average
# bc is bash calculator
avg=`echo "$sum / $m" | bc -l`
#k storing the modulus
k=$(( $m % 2 ))
if [ $k -eq 0 ] #if m is odd then median will be the middle index value of the sorted array
then
i=$(( $m / 2 )) #index
p1=$(( $i)) #first index
p2=$(( $i - 1)) #second index
s=$(( ${sortedarray[$p1]}+ ${sortedarray[$p2]} )) #sum of this 2
med=$(( s/2 )) #median
else #if even then median will be sum of middle 2 values divided by 2 of the sorted array
i=$(( $m / 2 )) #index
med=${sortedarray[$i]} #median
fi
echo "The array is : ${array[@]}"
printf 'Average %0.3f \n' "$avg"
printf 'Median %0.3f' "$med"
Tried with n=8