# sum of all digits in a given number using Shell Script

By: Dorris Emailed: 1697 times Printed: 2203 times

 By: rohit kumar - how this program is work By: Kirti - Hi..thx for the hadoop in By: Spijker - I have altered the code a By: ali mohammed - why we use the java in ne By: ali mohammed - why we use the java in ne By: mizhelle - when I exported the data By: raul - no output as well, i'm ge By: Rajesh - thanx very much... By: Suindu De - Suppose we are executing

This shell script prints the given number's sum of all digits, For eg. If no is 123 it's sum of all digit will be 1+2+3 = 6. ```#!/bin/bash # # Linux Shell Scripting Tutorial 1.05r3, Summer-2002 # # Written by Vivek G. Gite <vivek@nixcraft.com> # # Latest version can be found at http://www.nixcraft.com/ # # Algo: # 1) Input number n # 2) Set sum=0, sd=0 # 3) Find single digit in sd as n % 10 it will give (left most digit) # 4) Construct sum no as sum=sum+sd # 5) Decrment n by 1 # 6) Is n is greater than zero, if yes goto step 3, otherwise next step # 7) Print sum # if [ \$# -ne 1 ] then echo "Usage: \$0 number" echo " I will find sum of all digit for given number" echo " For eg. \$0 123, I will print 6 as sum of all digit (1+2+3)" exit 1 fi n=\$1 sum=0 sd=0 while [ \$n -gt 0 ] do sd=`expr \$n % 10` sum=`expr \$sum + \$sd` n=`expr \$n / 10` done echo "Sum of digit for numner is \$sum" ```

 1 View Comment`Thanx..very useful in this pgm..` View Tutorial          By: priya at 2013-02-06 10:54:44 2 View Comment`Thanks Friend it was very helpfull.` View Tutorial          By: UMAR FAROOQ at 2015-03-01 07:46:43 3 View Comment`Thanks :)` View Tutorial          By: Anuj Bhatnagar at 2015-05-06 14:02:19

Your email(required, will not be shown to the public):

More Tutorials by Dorris
 sum of all digits in a given number using Shell Script sh -x and sh -v in Linux case..esac..in Linux Shell Script while loop in Linux Shell Script Nested for loop in Linux Shell Script for loop in Linux Shell Script Multilevel if-then-else in Linux Shell Script Nested if-else-fi in Linux Shell Script if...else...fi in Linux Shell Script test command or [ expr ] in Linux Shell Script if condition in Linux Shell Script Download Linux. Which linux and where? Formula in Hibernate Primary keys assigned by triggers in Hibernate Assigned identifiers in Hibernate

More Tutorials in Linux