Adding the sum of digits in an integer

Write a program that displays the sum of the digits of any non-negative integer. Two program
runs are shown below:
Enter an integer: 145
Sum of digits is 10
Enter an integer: 8888
Sum of digits is 32

I can't figure out how to add them up. I'm probably not on the right track. Anything would be appreciated, thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()

{
    int X;

    cout << "Please input an integer: " << endl;
    cin >> X;


    for (int i=0; i < X; i++)
    X += i;
    
    cout << X;

    return 0;

}
closed account (E0p9LyTq)
http://www.cplusplus.com/forum/beginner/204434/#msg970245
Hint you will need to use modulus.

Your code will look something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()

{
	int num, result = 0;

	cout << "Please input an integer: " << endl;
	cin >> num;

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


	cout << result << endl;

	return 0;

}
Last edited on
Thank you for the help guys!
Topic archived. No new replies allowed.