Introduction
Given a five digit integer, print the sum of its digit
Input: 5 digit number, n
Output: sum of 5 digit number
Input and Output Format
# Input
10564
# Output
16
{: file="Sum Of Digits of a Five Digit Number.c” }
$1+0+5+6+4=16$
This is a watered-down version of the question
{: .prompt-info }
Process
This was my thought process while attempting this challenge.
- Calculate the number of digits
- By dividing the number by 10 and incrementing a counter in a while loop
- The number of digits can be found
- In a for loop to loop through the total number of digits (5)
sum += number % 10
number /= 10
- This is to remove the LSB of the number for each iteration of the loop
- Print out the sum
Code
|
|
{: file="Sum Of Digits of a Five Digit Number.c” }
Afterthoughts
I initially thought that I have to increment the mod divisor by 10 everytime (i.e. $10 \times 10 \times 10$) but soon realize that it is only going to make the number bigger.
I use the variable n
to calculate the number of digits and used the same variable to calculate the sum, this gave me a result of 0 cuz n
started from 0 in the loop!
I then realize I should probably initialize sum
to 0 cuz any uninitialized number will be given garbage, this would screw up the sum of numbers.