Wednesday, 17 April 2019

Write a shell script to print sum of digit of any number


Write a shell script to print sum of digit of any number
echo -n "Enter number : "
read n

# store single digit
sd=0

# store number of digit
sum=0

# use while loop to caclulate the sum of all digits
while [ $n -gt 0 ]
do
    sd=$(( $n % 10 )) # get Remainder
    n=$(( $n / 10 ))  # get next digit
    sum=$(( $sum + $sd )) # calculate sum of digit
done
echo  "Sum of all digit  is $sum"

Ouput:
[root@localhost shell_script]# bash sumofdigit.sh
Enter number : 123
Sum of all digit  is 6

No comments:

Post a Comment