2

I have to write a script where i need to show the sum of entered numbers and the biggest & smallest number among them. I am using array. I have solved this with normal way. but when i am using array i am getting sum, biggest number but can get the lowest number.I understand its because of my if logic for smallest number.

my script:

#!/bin/bash
sum=0
small=0
big=0

echo "Please enter the number"

while(( n != -99 ));
 do
        read -a n
        arr=${#n[@]}
     for((i=0;i<$arr;i++))do
     if [ ${n[$i]} -eq -99 ]; then
        break
     elif [ ${n[$i]} -ne -99 ]; then
     sum=$((sum + n[$i]))

     if [ ${n[$i]} -gt $big ]; then
     big=${n[i]}

    elif [ ${n[$i]} -le $small ]; then
     small=${n[i]}
    fi
   fi
    done
 done

echo "Sum: $sum"
echo "Highest: $big"
echo "Lowest:  $small"

output:

Please enter the number
12
13
14
-99
Sum: 39
Highest: 14
Lowest:  0
2
  • You're missing a $ before some of your i variables. Also get into the habit of always quoting your variables even if you think they don't need it. Commented Oct 12, 2017 at 11:43
  • @jimmij thanks... i tried with higher value.. but i got that same value which i have stored in small variable at first. for example, if initialize small=100 then i got lowest output 100 no matter what ever i have inserted less than hundred Commented Oct 12, 2017 at 11:59

1 Answer 1

0

This is working for me and I believe it is what you are trying to accomplish:

#! /bin/bash - 
NUM_SUM=0
NUM_LARGE=0
echo  "Please enter the numbers (-99 to exit):"

while [[ "$THIS_NUM" -ne '-99' ]]; do
    read -a THIS_NUM
    if [[ "$THIS_NUM" -ne '-99' ]]; then
        THIS_ARRAY+=("$THIS_NUM")
    fi
done
NUM_SMALL="${THIS_ARRAY[0]}"
for NUM in "${THIS_ARRAY[@]}"; do
    NUM_SUM=$((${NUM_SUM}+${NUM}))
    if [[ "$NUM" -gt "$NUM_LARGE" ]]; then
        NUM_LARGE="$NUM"
    elif [[ "$NUM" -lt "$NUM_SMALL" ]]; then
        NUM_SMALL="$NUM"
    fi
done
cat <<EOF
Summary:    $NUM_SUM
High Num:   $NUM_LARGE
Low Num:    $NUM_SMALL
EOF

I have this script ignoring the -99 input which I'm guessing you are only using as a way to exit the loop? With your input numbers I get the following output:

Please enter the numbers:
12
13
14
-99
Summary:    39
High Num:   14
Low Num:    12
1
  • yes -99 sentinel value to exit the loop...thanks a lot, i have found where i did the mistake...works 100%.it on the while loop for me... great man..you are a legend!!!! Commented Oct 12, 2017 at 14:34

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.