Program to find Sum of digits in C++
Written by
Many a times, we require to find the number of digits in a number or the sum of all digits of a number. In such cases, we can use the following method:
Algorithm:
- First, save the number in another variable for future use.
- Now get the last digit of the number by using % operator. It will provide the last digit as remainder.
- We add it to the sum of all digits.
- Now, divide the Original number by 10, to trim the last digit. (This is possible as the data type is int)
- We repeat the above steps until all digits of the original number are summed up.
Code:
#include<iostream> using namespace std; int main() { int num,rem; cin>>num; int duplicatenum=num; int sum=0, count=0; while(num!=0) // till all digits of num are dealt with { rem=num%10; //remainder,last digit extracted count++; sum=sum+rem; // add rem to sum num=num/10; //trimming last digit from num } cout<<"Sum of "<<duplicatenum <<" is "<<sum; cout<<"\nNumber of digits are:"<<count;
return 0; }
Output:
4567
Sum of 4657 is 22
Number of digits are:4