Wednesday 28 March 2018

Shell script to find the sum of odd and even numbers in an array separately


#shell script to sum the odd and even numbers in an array
echo "Enter the array elements "
read -a array
o=0
e=0
for((i=0;i<${#array[@]};i++))
do
    n=`expr ${array[$i]} % 2 `
    if [ $n -eq 0 ];then
          e=`expr $e + ${array[$i]}`
    else
          o=`expr $o + ${array[$i]}`
    fi
done
echo "The sum of even numbers in the given array.. $e"
echo "The sum of odd numbers in the given array..   $o"


OUTPUT
csc@csc-SVE1513CYNB ~ $ bash oddeven02.sh
Enter the array elements
1 2 3 4 5 6 7 8 9
The sum of even numbers in the given array.. 20
The sum of odd numbers in the given array.. 25

No comments:

Post a Comment