Bash shell script to find sum of digits
Given a number Num, find the sum of digits of the number.
Examples:
Input : 444 Output : sum of digits of 444 is : 12 Input : 34 Output : sum of digits of 34 is : 7
Approach:
1. Divide the number into single digits 2. Find the sum of digits .
Bash
# !/bin/bash # Program to find sum# of digits # Static input of the# numberNum=123g=$Num # store the sum of # digitss=0 # use while loop to# caclulate the sum# of all digitswhile [ $Num -gt 0 ]do # get Remainder k=$(( $Num % 10 )) # get next digit Num=$(( $Num / 10 )) # calculate sum of # digit s=$(( $s + $k )) doneecho "sum of digits of $g is : $s" |
Output
sum of digits of 123 is : 6


