Shell Script to Find Sum of Digits

This shell script is used to find the sum of Digits. If the given number is 23 then the sum will be 2+3 = 5. The script is explained below:

Example:
Given Number is: 23.
Then n=23.
First Iteration:
sd=3
n=2
sum=2
—–
Second Iteration:
sd=2
n=0
sum=5

echo "Enter a Number:"
read n

temp=$n
sd=0
sum=0

while [ $n -gt 0 ]
	do
		sd=$(( $n % 10 ))
		n=$(( $n / 10 ))
		sum=$(( $sum + $sd ))
	done
echo "Sum is $sum"

Output:
sumofn

Leave a Reply