0

Help with adding all the digits in an integer together; C++

Does anyone know how to add all the digits in an integer together. Example, you have the number 1234. You then add all the digits i.e. 1+2+3+4=10.

18th Nov 2016, 5:04 PM
Abdullah Bemath
Abdullah Bemath - avatar
7 Respostas
+ 3
Take numbers input in string and than add them like #include <iostream> using namespace std; int main() { string s; int i,sum; cout << "Please enter a digit " << endl; cin >> s; cout << "You have entered " << s << endl; sum=0; for(i=0;i<s.size();i++) sum+=(s[i]-48); cout << "Your data is " << sum; return 0; }
18th Nov 2016, 5:26 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 1
Here is the code to my suggested solution (seems simpler, now that I've written it:-)) #include <iostream> using namespace std; int main() { cout <<"Enter the number: " << endl ; int num; cin >> num; int sum = 0; int q = num; //temporary variable to hold the number since I don't want to modify it while(q > 0){ sum += q % 10; q = q / 10; } cout << "The sum of digits of " << num << " equals " << sum <<endl; return 0; }
18th Nov 2016, 7:32 PM
Rill Chritty
Rill Chritty - avatar
0
I understand all of it except this part "sum+=(s[i]-48);" . Why did you subtract 48?
18th Nov 2016, 5:35 PM
Abdullah Bemath
Abdullah Bemath - avatar
0
ASCII code of a digit char minus 48 gives the numerical value of that digit (from the fact, that the ASCII code of '0' is 48), for instance ASCII code of the character '8' is 56, so 56 - 48 gives 8, the numerical value of the digit 8
18th Nov 2016, 7:10 PM
Rill Chritty
Rill Chritty - avatar
0
Though not as simple as the solution by Aditya, you can solve the problem by repeated successive modulus and integer division by 10. I will try to write the code later.
18th Nov 2016, 7:13 PM
Rill Chritty
Rill Chritty - avatar
0
Thanks
18th Nov 2016, 7:17 PM
Abdullah Bemath
Abdullah Bemath - avatar
0
I see. Thanks
18th Nov 2016, 7:57 PM
Abdullah Bemath
Abdullah Bemath - avatar