In: Computer Science
Suppose a file (whose name is given through an argument by the user) contains student names and their scores (ranging from 0 to 100): i.e. each line contains a student name (just the first name with no space inside) and the student’s score separated by a space. Find out who has the highest score with what score, and who has the lowest score with what score. Also, calculate the average of all of the scores. Do not use arrays to solve this problem. (bash shell)
awk 'BEGIN {
FS=" ";min=0;max=0;total=0;
}
{
if(NR==1)
{
name_highscore=$1;
name_lowscore=$1;
min=$2;
max=$2;
total=total+$2;
}
else
{
if($2>max)
{
max=$2;
name_highscore=$1;
}
else if($2<min)
{
min=$2;
name_lowscore=$1;
}
total+=$2;
}
}
# End Block
END {
avg_score=total/FNR;
printf("The student with highest score is %s and the score is %d\n",name_highscore,max);
printf("The student with lowest score is %s and the score is %d\n",name_lowscore,min);
printf("The average score of all students is %d\n",avg_score);
}'
As mentioned in the question, we are not making use of arrays in the above code. We just take to variables min and max and keep on checking for every input. The same applies as well for the names (i.e student name with highest score and lowest score). At last in END block we calculate average score using total and FNR. Then we print the results using printf statements. Please feel free to ask doubts if any, in the comments section.
I am also attaching the input and output for your reference.
Input: The following is the sample input (student.txt) for above code
Mukesh 89
Balaram 77
Shawn 99
Demon 87
Output: The following is the output for above input.
Please dont forget to upvote if you like my work. This will help me to provide better solutions with great effort.