'shell script to print sum of digits of the given num.In case of negative num is given as input, display Not a positive num as o/p
I'm getting the proper output, but only for positive inputs.
read n
g=$n
s=0
k=
if [ $n -gt 0 ] ; then echo "Not a positive number"
else
while [ $n -gt 0 ]
do
k=$CC $n % 10 ))
n=$CC $n / 10 ))
s=$(C $s + $k ))
done
echo "Sum of digit for given number is $s"
fi
Solution 1:[1]
This will do the work
read a
s=0
if [[ $a -lt 0 ]]
then
echo "Not a positive number"
else
while [[ $a -gt 0 ]]
do
k=$(( $a % 10 ))
a=$(( $a / 10 ))
s=$(( $k + $s ))
done
echo "Sum of digit for given number is $s"
fi
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |