Adding the sum of the digits in an integer

Oct 19, 2008 at 11:23pm
Hello, I read that I'm not supposed to ask for the solution to homework assignments, which is fine by me. I'd rather work out the problem myself, else I'll never be able to make it on my own.

However, that being said, I'm having some difficulty with my latest assignment.

We are instructed to use a for loop to add the sum of the digits in an integer. So, 3426 would be 3 + 4 + 2 + 6 = 15. Simple enough, right? I thought so... But now I'm not so sure.

So, what I have done is use the % operator (number%10) to get the value of the last digit and I store it to numbersum (type int).

The problem I am encountering is trying to get it to read the next digit after that. In other words, for 3426, it's reading the 6 just fine, but it won't read the 2, 4, or 3.

As we are not allowed to use any functions, would someone please be so kind as to explain which method or operation I might be able to use to get my program to read the next digits in my integer?

Thank you!
Oct 19, 2008 at 11:45pm
if it is an int, you could just do something like this...
3426 % 10 gets you the 1's, now divide by 10, its a decimal... the decimal gets dropped off for the next part of the for loop. so it would just repeat.
assuming its only 4 digits, no more no less,
1
2
3
4
5
6
7
8
int number
int numbersum = 0
int x = 1
cin >> number
for (x = 1; x <= 4; ++x){
numbersum = numbersum + number % 10
number = number / 10
}

obviously, this wouldn't be finished code, but it would get the results you want.
Last edited on Oct 19, 2008 at 11:55pm
Oct 20, 2008 at 4:39am
omegazero was kind enough to give you some potentially confusing code rather than the answer :). The answer is in there though.

What is the result of 3426 / 100? How about 3426 / 1000? How about 3426 / 10000? Understanding that pattern, combined with understanding the % operator, and a loop, should form together into your solution.
Oct 20, 2008 at 12:42pm
This is your solution -

#include <iostream>

using namespace std;

int main()
{
int num;
int sum = 0;

cout << " Enter a number : ";
cin >> num;

while ( num > 0 ) {
sum += num % 10;
num /= 10;
}

cout << "Sum = " << sum;

return 0;
}
Oct 21, 2008 at 10:36pm
Thanks everyone! I actually gathered the concept from the first response. It went off in the back of my head kind of like a gong. I suppose that sometimes I just have issues seeing the simpler solutions to things.
Oct 22, 2008 at 8:01pm
Actually, from a certain point of view, you all are wrong. This is impossible.

All operators are functions in disguise.

x + y is actually x.operator+(y), or operator+(x, y), or whatever.

I realize this is unnecessary, but I needed to find someplace to vent my anger. Yay!
Last edited on Oct 22, 2008 at 8:01pm
Topic archived. No new replies allowed.