The summation of digits

My teacher gave a study guide with the problem,

"Int x is loaded with some numbers (how many is irrelevant.) Show the code that will sum the digits of x."

He wrote this code on the board:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<cstdlib>
#include<cmath>

using namespace std;

int main()
{
	int x, accum = 0;
	
	while(x > 0)
	{
		accum = x % 10;
		x = x / 10;
	}
}


I must have copied it wrong because there is no addition in this code. I'm having trouble trying to figure out what I missed. Any thoughts?
You have the parts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<cstdlib>
#include<cmath>

//not needed for this program and in general bad practice
using namespace std;

int main()
{
	int x, accum = 0; //accum is the sum of your x digits
	
	while(x > 0)
	{
		accum = x % 10; //sets the last place digit of x into accum
                                          //ex. x = 1234 now accum = 4
                                          //this is overwritten for every iteration of your 
                                          //loop and needs to be stored
		x = x / 10;          //sets x to the number without last placed digit
	                                  //ex. 1234 now x = 123
         }
}


Basically, you need to code it so accum not only grabs the last digit but also stores the previous digit. This is done with addition arithmetic and is identical to thought behind x += 1.
Last edited on
I kinda feel silly! I changed it so that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<cstdlib>
#include<cmath>

using namespace std;

int main()
{
	int x, num = 0, accum = 0;
	x = 666;
	
	while(x > 0)
	{
		num = x % 10;	//changed the orginal variable to num
		accum += num;	//added the addition
		x = x / 10;
	}
	cout << accum;
}


thank you!
No problem and if you wanted to shorten it, you could use accum
as num.

1
2
accum += (x%10);
//accum = accum + (x%10); 
Topic archived. No new replies allowed.