Thursday, November 1, 2012

How to find the sum of digits in the number in Unix


###########################################################
# To find the sum of digits in the number                 #
###########################################################

#!/bin/ksh

# Checking the required arguments
if [ $# -ne 1 ]
 then
   echo "Please provide one argument"
exit -1
fi

# assigning the arguments to the local variables
a=$1
s=0

# Logical part to find the sum of digits in the number
while [ $a -gt 0 ]
do
b=$(( $a%10 ))
s=$(( $s+$b ))
a=$(( $a/10 ))
done

echo "The sum of digits in $1 is $s"
exit 0