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.
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;
}
+ 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;
}
0
I understand all of it except this part "sum+=(s[i]-48);" .
Why did you subtract 48?
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
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.
0
Thanks
0
I see. Thanks