In: Computer Science
Code the following in bash and run. Please show full code and don’t forget to comment your code.
Make a code that takes any list of numbers and calculates and displays the mean, median and mode.
Mean is also called average. The program to calculate mean is:
# Total numbers
n=5
# copying the value of
n
m=$n
# initialized sum by
0
sum=0
# array initialized
with
# some numbers
array=(1 2 3 4 5)
# loop until n is
greater
# than 0
while
[ $n -gt 0 ]
do
# copy element in
a
# temp
variable
num=${array[`expr $n
- 1`]}
# add them to
sum
sum=`expr $sum +
$num`
# decrement count of
n
n=`expr $n -
1`
done
# displaying the average
# by piping with bc command
# bc is bash calculator
# command
avg=`echo
"$sum / $m"
| bc
-l`
printf
'%0.3f'
"$avg"
To compute median:
!/bin/bash # This program computes the median of a list of integers on the command line. # If there are no arguments, then it asks the user to enter them on # separate lines. Then it prints the median (middle # value after sorting). If there are an even number of numbers, then # the median is the average of the 2 middle values, rounding down # Copy the command line into array n i=0 # current element of n finished=0 # 1 (true) when there is no more interactive input expected while (($# > 0)); do ((n[i] = $1)) shift ((i++)) finished=1 done # Else if there are no arguments then ask the user to enter some numbers if ((!finished)); then echo Enter some numbers, one per line. Enter a blank line when done. while ((!finished)); do read x if [ "$x" == "" ]; then finished=1 else ((n[i++]=x)) fi done fi # If n is empty then give up size=${#n[*]} if ((size==0)); then echo Error: at least one number is expected exit 1 fi # Bubble sort n ((i=size-1)) while ((i>0)); do j=0 while ((j<i)); do if ((n[j]>n[j+1])); then #swap so n[j] <= n[j+1] ((t=n[j])) ((n[j]=n[j+1])) ((n[j+1]=t)) fi ((++j)) done ((--i)) done # Compute the median from the middle 1 or 2 elements ((mid = size/2)) if ((size % 2 == 0)); then ((median = (n[mid] + n[mid-1]) / 2)) else ((median = n[mid])) fi # Print the sorted array and the median echo The median of ${n[*]} is $median