0

How to find the sum of digits of an integer using c++?

its important...i have exam

31st Jan 2017, 3:07 PM
Arjun Praveen
Arjun Praveen - avatar
4 ответов
+ 6
int sum=0;int nums[]={1,2,3,4,5};/*find a way to split your num to this format…*/for(int stp=0;stp<nums.length;stp++){sum+=nums[stp];}
31st Jan 2017, 3:14 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 2
yes i got a simple way #include <iostream> using namespace std; int main() { int n,rem,s=0; cout<<"enter a number="; cin>>n; while(n>0) {rem=n%10; s=s+rem; n=n/10; } cout<<"sum of digit is"<<s; return 0; }
31st Jan 2017, 3:15 PM
Arjun Praveen
Arjun Praveen - avatar
+ 2
convert it to string, then use .length() method. If that's not the case, use modulus operator just like @Arjun has written.
31st Jan 2017, 3:54 PM
Jakub Stasiak
Jakub Stasiak - avatar
+ 1
I'll give you a hint: any number modulo 10 will give you the last digit. For instance, 496 % 10 = 6. While I'm at it, here's another: Every time you get a digit from the number, divide by 10 and round down. You can do this with the "floor()" function using the cmath header. Do it like this: n = (int) floor(n / 10).
31st Jan 2017, 3:21 PM
DaemonThread
DaemonThread - avatar