LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   addition using array values into a variable not possible? (https://www.linuxquestions.org/questions/programming-9/addition-using-array-values-into-a-variable-not-possible-914726/)

olof_ 11-21-2011 11:19 AM

addition using array values into a variable not possible?
 
Hi there.

I am trying to add every value in an array together in a single variable. The script is working, but throws an error:

syntax error: operand expected (error token is "+")
Is it not possible to add values from an array into a non-array variable?

Code:

echo Input some numbers, separated by a space please:
read -a choice

amount=${#choice[@]}

for a in `seq 0 $amount`; do
sum=$(($sum+${choice[$a]}))
done

echo The result after adding all numbers is: $sum

Thanks in advance.

firstfire 11-21-2011 11:36 AM

Hi.
This should work:
Code:

echo Input some numbers, separated by a space please:
read -a choice

amount=${#choice[@]}

for a in `seq 0 $amount`; do
sum=$((sum + choice[$a]))
done

echo The result after adding all numbers is: $sum


grail 11-21-2011 11:52 AM

There is some more overhead that is not really required:
Code:

#!/bin/bash

echo Input some numbers, separated by a space please:
read -a choice

for a in ${!choice[*]}
do
    ((sum+=choice[a]))
done

echo The result after adding all numbers is: $sum


olof_ 11-21-2011 02:44 PM

Thank you very much!
Really impressively quick answers.

David the H. 11-21-2011 04:00 PM

Or how about this?

Code:

$ choice=( 1 2 3 4 5 )
$ IFS=+

$ echo $(( ${choice[*]} ))
15

It may not work correctly with negative numbers though.


All times are GMT -5. The time now is 06:14 AM.