$ cat score pchen72 50 71 55 93 115 jmaszk 45 76 49 88 102 bvbui 59 78 53 96 145
ID: 3670532 • Letter: #
Question
$ cat score
pchen72 50 71 55 93 115
jmaszk 45 76 49 88 102
bvbui 59 78 53 96 145
mtcrowle 33 65 39 82 100
mrchave3 54 77 56 98 158
Write an awk script that computes the average score for each student, as well as the class average. You are to define a function that accepts an array as parameter, compute and return the average of its elements In the processing block, assign each field (except the first) as element of an array, then pass that array to the function.
The output should be :
pchen72 76.8
jmaszk 72
bvbui 86.2
mtcrowle 63.8
mrchave3 88.6
END OF FILE
Explanation / Answer
See the code below:
------------------------------------------------
function calculate_average(scores_list)
{
sum=0
for(i in scores_list)
sum+=scores_list[i]
average = sum/length(score_list)
return average
}
BEGIN {i=1}
{getline; scores[i]=$0; i++} score.txt
END {
for (i=1;i<=length(scores);i++)
{
split(scores[i],arr," ")
k=1;
scores_list[k]=0
name=""
average_sum=0
for(j=1; j<=length(arr);j++)
{
if(j==1)
name = arr[j]
else
{
scores_list[k]=arr[j]
k++
}
}
average=calculate_average(scores_list)
average_sum+=average
print(name, " ", average)
}
class_average=average_sum/i
print("Class average:",class_average)
}
------------------------------------------------
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.