What is sum of digits?
Sum of digits means adding all the digits of a number together.
πΉ Example 1:
Number: 123
Digits: 1, 2, 3
Sum: 1 + 2 + 3 = 6
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum = sum + digit;
num = num / 10;
}
Start
|
v
Get number from user β num = 456
|
v
Set sum = 0
|
v
ββββββββββββββββββββββββββββββββββββββ
| Check: num > 0? (456 > 0) |
| |
| 1st Iteration: |
| digit = num % 10 = 456 % 10 = 6 |
| sum = sum + digit = 0 + 6 = 6 |
| num = num / 10 = 456 / 10 = 45 |
| |
| 2nd Iteration: |
| digit = 45 % 10 = 5 |
| sum = 6 + 5 = 11 |
| num = 45 / 10 = 4 |
| |
| 3rd Iteration: |
| digit = 4 % 10 = 4 |
| sum = 11 + 4 = 15 |
| num = 4 / 10 = 0 |
| |
| num = 0 β exit loop |
ββββββββββββββββββββββββββββββββββββββ
|
v
Print "Sum of digits = 15"
|
v
End
Simple example and diagram
Step-by-Step (with Diagram)
Letβs take an example number: 469
ββββββββββββββ
β Number β
β 469 β
ββββββ¬ββββββββ
β
βββββββββΌβββββββββ
β Get last digit β 469 % 10 = 9
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Add to sum β sum = 0 + 9 = 9
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Remove last β 469/ 10 = 46
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Repeat β 46 % 10 = 6 sum = 9 + 6 = 15
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Repeat β 4 % 10 = 4, sum = 15 + 4 = 19
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Number is 0 β
β Stop process β
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Final Answer β
β 19 β
ββββββββββββββββββ
Here's a step-by-step breakdown:
*Get the number: Input the number for which you want to calculate the sum of digits.
*Initialize sum: Create a variable (e.g., sum) and set its initial value to 0.
*Loop through the digits:
Extract the last digit: Use the modulo operator (%) to get the remainder when the number is divided by 10. *This gives you the last digit.
*Add to the sum: Add the extracted digit to the sum variable.
*Remove the last digit: Divide the number by 10 (integer division) to remove the last digit.
*Repeat: Continue this process as long as the number is greater than 0.
*Return the sum: Once the number becomes 0, the sum variable will hold the sum of all the digits.
Example:
*Let's say the input number is 123.
sum = 0
last_digit = 123 % 10 = 3
sum = 0 + 3 = 3
number = 123 / 10 = 12
last_digit = 12 % 10 = 2
sum = 3 + 2 = 5
number = 12 / 10 = 1
last_digit = 1 % 10 = 1
sum = 5 + 1 = 6
number = 1 / 10 = 0
The loop terminates because number is no longer greater than 0.
The sum of digits is 6.
https://www.101computing.net
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)