Wednesday, March 19, 2014

Sum of Digits – Linux Shell Scripting

Problem Question


Write a script to calculate the sum of digits of the given number.

Explanation of Problem


Here we wish to write a Linux Shell Script that would accept one command line parameter (integer) and find the sum of it’s digits. Thus, in a sample run like:
sh SumOfDigits.sh 123
the output should be 6.

Code



#*SumOfDigits*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 19-03-2014
x=$1
a=0
b=0
while [ $x -gt 0 ]
 do
  a=$(( $x % 10 ))
  x=$(( $x / 10 ))
  b=$(( $b + $a ))
 done
echo Sum of digits of $1 is $b

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

x=$1 -> We save the command line argument into a variable named ‘x’. This variable is required since we are going to use it to segregate the digits by recursively dividing it with 10 and storing the remainder.

a=0 b=0 -> We use the variable ‘a’ to store the remainder using a=$(( $x % 10 )) and variable ‘b’ to store the sum using b=$(( $b + $a )).

while [ $x -gt 0 ] -> We use this while loop to do the operations stated above. Apart from that, we divide ‘x’ by 10 using x=$(( $x / 10 )) everytime in the loop and store the answer in ‘x’ because we want to reject the last digit as soon as we have stored it in variable ‘a’.

do done -> While loop block delimiters.

echo Sum of digits of $1 is $b -> echo command of the linux shell is then used to display the string following it. ‘$1’ implies the first command line argument, and ‘$b’ the sum we were required to calculate.

Output(s)



No comments:

Post a Comment

Need help?