How do I find the sum of values from two arrays?

Hi

I have redc[] containing the values 3, 6, 2, 8, and 1.

I have work[] containing the values 8, 2, 11, 7, and 9.

Is there a way to find the sum of redc and work?

I need to compare the sum of those two arrays to something else, so is it okay to put that into my END?

TY!

Seems a few of us answered this question already:

Yes, you can put it in the END block of code.

perl -e '@x=(3,6,2,8,1);@y=(8,2,11,7,9);for($i=0;$i<=$#x;$i++){$sum+=($x[$i]+$y[$i])};print $sum'
1 Like

I hope it will help you to solve the summation part and I believe comparison part you can do it yourself :slight_smile:

redc=(3 6 2 8 1)
work=(8 2 11 7 9)

function sum {
        local sm=0
        local tmp
        tmp=(`echo "$@"`)

        for i in ${tmp
[*]}
        do
                sm=$[ $sm + $i ];
        done
echo $sm
}

echo "The Sum of redc is :: " ; sum ${redc
[*]}
echo "The Sum of work is :: " ; sum ${work
[*]}

You can do it without temp arrays - use argument and shift it.

redc=(3 6 2 8 1)
work=(8 2 11 7 9)

sum()
{
        sm=0
        while [ $# -gt 0 ]
        do
                val=$1
                shift
                ((sm+=val))
        done
        echo $sm
}

echo "The Sum of redc is :: $(sum ${redc
[*]} ) "
echo "The Sum of work is :: $(sum ${work
[*]} ) "