Compute the Average HackerRank Solution

Hello Programmers, In this post, you will know how to solve the Compute the Average HackerRank Solution. This problem is a part of the HackerRank Linux Shell Series.

Compute the Average HackerRank Solution
Compute the Average HackerRank Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Problem

Given N integers, compute their average, rounded to three decimal places.

Input Format

The first line contains an integer, N.
Each of the following N lines contains a single integer.

Output Format

Display the average of the N integers, rounded off to three decimal places.

Input Constraints

  • 1 <= N <= 500
  • -10000 <= x <= 10000 (x refers to elements of the list of integers for which the average is to be computed)

Sample Input

4
1
2
9
8

Sample Output
5.000

Explanation

The ‘4’ in the first line indicates that there are four integers whose average is to be computed.
The average = (1 + 2 + 9 + 8)/4 = 20/4 = 5.000 (correct to three decimal places).
Please include the zeroes even if they are redundant (e.g. 0.000 instead of 0).

Compute the Average HackerRank Solutions

#!/bin/bash
#Easier way is to do using for loop
read num
ctr=$num
sum=0
while [ $ctr -gt 0 ]
do
   read x
   sum=$((sum + x))
   ctr=$((ctr - 1))
done
printf "%.3f\n" `echo "$sum/$num" | bc -l`

Note: This problem (Compute the Average) is generated by HackerRank but the Solution is Provided by  BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Functions and Fractals Recursive Trees Bash! HackerRank Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad