Before this post you should learn

1. Basic bash hackerrank

2. Shell beginner

# 1 example to solve

Q1.Given N integers, compute their average correct to three decimal places using Bash

Solution is very simple as we know average= sum of all numbers/ count of numbers

so we take an input that is count of numbers, then using while/for loop we read all numbers and added it in a variable sum, after that we divide it by count and used 3 decimal value

```
read n
sum=0
let temp=$n
until [ $n -eq 0 ]
do
read x
sum=$(($sum + $x))
((n--))
done
printf "%.3f" $(echo "$sum / $temp" | bc -l)
```

```
read n
sum=0
for ((i=0;i<$n;i++))
do
read temp
sum=`$(($`sum+$temp))
done
printf "%.3f\n" `$(bc -l <<< "$`sum/$n")
```

1 more solution using array concept easy

```
read n
arr=($(cat))
arr=${arr[*]}
printf "%.3f" $(echo $((${arr// /+}))/$n | bc -l)
```

uses array for list,arr=($(cat)) -> reads in the array [1,3,5,6]

arr=${arr[*]} -> render a new variable of type string from the merging of the array arr delimited by space, i.e., from [1,3,5,6] to “1 3 5 6”

${arr// /+} -> replaces all spaces ‘ ‘ in the string variable with + ,i.e., we get “1+3+5+6”

$((exp)) -> evaluates the expression “exp” by performing arithmetic operations, here “exp” => ${arr// /+}. Thus + is treated as arithmetic operator and the string is evaluated sequentially form left to right. We get, 1+3+5+6 = 4+5+6 = 9+6 = 15

```
sum=0
read n
while read -r line || [[ -n "$line" ]]; do
sum=$(($sum + $line))
done
printf "%.3f" $(echo "scale=10; $sum/$n" | bc -l)
```

## Basic bash concepts II and Hackerrank Solution

Q2. if statements in Bash are often used in four important ways:

1. if…then…fi statements

2. if…then…fi…else statements

3. if..elif..else..fi

4. if..then..else..if..then..fi..fi.. (Nested Conditionals)

Given three integers (X, Y, and Z) representing the three sides of a triangle, identify whether the triangle is Scalene, Isosceles, or Equilateral.

Sample Input 1

2

3

4

Sample Output 1

SCALENE

Sample Input 2

6

6

6

Sample Output 2

EQUILATERAL

```
read a
read b
read c
if [ "$a" -eq "$b" ] && [ "$a" -eq "$c" ]
then
echo "EQUILATERAL"
elif [ "$a" -eq "$b" ] || [ "$a" -eq "$c" ]
then
echo "ISOSCELES"
else
echo "SCALENE"
fi
```

```
read a
read b
read c
if [ `$a -eq $`b ] && [ `$a -eq $`c ]; then
echo "EQUILATERAL"
elif [ `$a -eq $`b ] || [ `$a -eq $`c ] || [ `$b -eq $`c ]; then
echo "ISOSCELES"
else
echo "SCALENE"
fi
```

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme