10 January 2012

Shell Script to Find Sum of Digits of a Number

1 comment

Q. How do I write Shell Script to find Sum of digits of a Number


Ans:

#!/bin/bash
echo -e "enter the number"
read n
sum=0
a=$n
while(($n >0))
do
x=`expr $n % 10`
sum=`expr $sum + $x`
n=`expr $n / 10`
done
echo "the sum of $a is $sum"


Output


shell script to find sum of digits of a number

Enjoy :)


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

1 comment:

  1. Shorter way..


    DIGITS=1234567890
    SUM=0
    for i in $(seq ${#DIGITS})
    do SUM=$(($SUM + ${DIGITS:$i-1:1}))
    done
    echo $SUM

    ReplyDelete