Bash Script to Find Sum of Digits of a Number
Use a Bash script that reads a number and sums its digits by looping through each digit with
while and modulus operations, like: while [ $num -gt 0 ]; do sum=$((sum + num % 10)); num=$((num / 10)); done.Examples
Input123
Output6
Input0
Output0
Input99999
Output45
How to Think About It
To find the sum of digits, think of the number as a collection of single digits. Extract each digit by taking the remainder when divided by 10, add it to a sum, then remove that digit by dividing the number by 10. Repeat until the number is zero.
Algorithm
1
Get the input number.2
Initialize sum to zero.3
While the number is greater than zero:4
Extract the last digit using modulus 10.5
Add the digit to sum.6
Remove the last digit by dividing the number by 10.7
Return the sum.Code
bash
#!/bin/bash read -p "Enter a number: " num sum=0 while [ $num -gt 0 ]; do digit=$((num % 10)) sum=$((sum + digit)) num=$((num / 10)) done echo "$sum"
Output
6
Dry Run
Let's trace input 123 through the code
1
Initial values
num=123, sum=0
2
First iteration
digit=3, sum=3, num=12
3
Second iteration
digit=2, sum=5, num=1
4
Third iteration
digit=1, sum=6, num=0
| num | digit | sum |
|---|---|---|
| 123 | 3 | 3 |
| 12 | 2 | 5 |
| 1 | 1 | 6 |
Why This Works
Step 1: Extract digit
Using num % 10 gets the last digit of the number.
Step 2: Add to sum
Add the extracted digit to the running total stored in sum.
Step 3: Remove digit
Divide the number by 10 using integer division to remove the last digit.
Alternative Approaches
Using string manipulation
bash
#!/bin/bash read -p "Enter a number: " num sum=0 for (( i=0; i<${#num}; i++ )); do digit=${num:i:1} sum=$((sum + digit)) done echo "$sum"
This method treats the number as a string and sums digits by indexing, which is simpler but less arithmetic-focused.
Using awk command
bash
read -p "Enter a number: " num echo "$num" | awk '{sum=0; for(i=1;i<=length($0);i++) sum+=substr($0,i,1); print sum}'
This uses awk to sum digits, useful for quick one-liners but depends on external tool availability.
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs once per digit, so time grows linearly with the number of digits, O(n).
Space Complexity
Only a few variables are used regardless of input size, so space is constant, O(1).
Which Approach is Fastest?
Arithmetic looping is fast and memory efficient; string methods are easy but slightly slower due to string handling.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic loop | O(n) | O(1) | Efficient numeric processing |
| String manipulation | O(n) | O(1) | Simple code, easy to read |
| awk command | O(n) | O(1) | Quick one-liners, external tool dependent |
Always initialize your sum variable to zero before starting the loop to avoid unexpected results.
Forgetting to update the number by dividing by 10 inside the loop causes an infinite loop.