Sum of digits of a number
Finding the sum of individual digits in a number
Learning Objectives
- Digit extraction and summing of digits using the loop operations.
Source Code
|
|
Alternate (?) : Related ( ? ) : |
Run Output
Code Understanding
int nc=n;
After collecting the number from users in the variable n this is an important step as a working copy of the number has to be created in the variable nc. This working copy will be used for further operation so that the original value is retained in n. This has to be understood that digit extraction process is a kind of destructive process which doesn’t retain the number in its original form once the loop is complete.
while(nc>0)
This loop keep working till no more digit is left to used.
digit=nc%10;
Here we extract 1 single digit from the last using the % division as only remainder is left.
sum=sum+digit;
Here we add the extracted digit to previously summed value. In the first iteration this will be equal to the last digit only as the sum is initialised with 0.
nc=nc/10;
This operation removes the last digit as this is an integer division.
cout<<“Sum of Digits of “<<n<<” = “<<sum<<endl;
This we can print after the loop is over.
Notes
- Sum of digits can have many variations like, sum of squares of number, sum of cubes of a 3 digit number, product of digits etc. The core technique remains the use of % and / operator and then a formula on individual digits and the operations on all set of digits will result. This type of loop purpose is used in many applications like Armstrong number, narcissist number, palindrome number etc.
Common Errors
- Some time students forget to initialise sum with 0 while declaring.
Suggested Filename(s): sum-of-digits.cpp, sumdig.cpp
Created: 2-Jan-2018 17:01 | Updated: 15-Sep-2018 12:42|
