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 # number Num=123 g=$Num # store the sum of # digits s=0 # use while loop to # caclulate the sum # of all digits while [ $Num -gt 0 ] do # get Remainder k=$(( $Num % 10 )) # get next digit Num=$(( $Num / 10 )) # calculate sum of # digit s=$(( $s + $k )) done echo "sum of digits of $g is : $s" |
chevron_right
filter_none
Output
sum of digits of 123 is : 6
Recommended Posts:
- Bash shell script to find out the largest value from given command line arguments
- Bash shell script to swap two numbers
- String Operators | Shell Script
- Looping Statements | Shell Script
- Conditional Statements | Shell Script
- Bash Script to get Low Battery Alert in Linux
- Implementing Directory Management using Shell Script
- Write a bash script to print a particular line from a file
- Automated Recursive Encryption in a Directory Using Shell Script
- Introduction to Linux Shell and Shell Scripting
- Bash program to find A to the power B
- A Shell program To Find The GCD | Linux
- How to find time taken by a command/program on Linux Shell?
- Fibonacci Series in Bash
- Simple Calculator in Bash
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.