Friday, March 14, 2014

Average of n numbers - Linux Shell Scripting

Problem Question


Write a script to calculate the average of n numbers

Explanation of Problem


Here we wish to write a Linux Shell Script which when executed any number of command line arguments, calculates their average(integer value only). So if the script is executed as the following, the outputs would be as under.

sh AverageCalculator.sh

ERROR

sh AverageCalculator.sh 1

1

sh AverageCalculator.sh 1 2

1

sh AverageCalculator.sh 1 2 3

2

sh AverageCalculator.sh 1 2 3 4 5 23 234 234 234 23 234 235 123 14

97

Code



#*Average Calculator*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 14-03-2014

sum=0
for i in $*
 do
  sum=`expr $sum + $i`
 done
avg=`expr $sum / $#`
echo $avg

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

sum=0 -> We declare a variable 'sum' and initialize it to value zero. We will be using it for holding the sum of all the values passed as command line arguments.

for i in $* -> Here we initialize a for loop which travels through the whole list in the command line. '$*' imply the list of command line arguments. 'i' is the loop counter variable we have introduced. It could have been anything else than 'i' also.

sum=`expr $sum + $i` -> We tell the shell to store the value of the expression, (sum + i) in the variable sum. We repeat this since we are in a 'for' loop. Thus we get the sum of all the numbers in the command line arguments list.

avg=`expr $sum / $#` -> '$#' implies the number of command line arguments. Thus, we introduce a new variable named 'avg' that would hold the integer value returned by the division of 'sum' and '$#'.

echo $avg -> echo command writes the value following it to the standard display terminal.

do done -> do and done are the delimiters of the loop block. They can be understood similar to the {}braces in C/C++.

Output(s)



No comments:

Post a Comment

Need help?