Write a program to output the sum and single digits of any integer

I'm having a hard time writing a correct LCV for the while loops in my program. Also, could someone provide an explanation as to why my program freezes after it prompts the user to input an integer?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  #include <iostream>
  #include <cmath>

using namespace std;

int main()
{
	int num, num2, sum = 0;
	int div, num3, count = 0;

	cout << "Enter an integer: ";
	cin >> num;
	cout << endl;                 //This is where it freezes.

	count = 0;

	while (num != 0)
	{
		num2 = num / 10;
		count++;                //Needs appropriate LCV
	}

	num = num2;

	do
	{
		div = static_cast<int>(pow(10, --count));       //Not sure
		num3 = num2 / div;                                 //if this is the 
		num2 = div % div;                                //right equation

		cout << num3 << ' ';
		sum = sum + num3;
	}

	while (count != 0);                                            // I think this is 
	cout << "The sum of the integers is: " << sum   // the only right 
		<< endl;                                          // right thing about
	                                                                     // the whole program
	return 0;
}
Last edited on
Deactivate line 13 and run!
What do you mean deactivate line 13 when its only a end line statement. That's not going to help me at all.
Last edited on
1
2
3
4
5
while (num != 0)
	{
		num2 = num / 10;
		count++;                //Needs appropriate LCV
	}

This is an endless loop. Your num is never going to get back to 0 to exit the loop. num variable never changes, so it has no chance to exit the first loop at all! Put cout<<count<<endl; in there, and you'll see. I think that's seriously it...That's the only issue I can see, although I'm not sure if the --count is right syntax. I always used x+=1 or x-=1, etc.

I'll be honest, I'm not sure what num!= 0 is trying to accomplish.
Last edited on

1
2
3
4
5
6
while (num != 0)
	{
		num2 = num / 10;
		count++;                //Needs appropriate LCV
	}
  


it means that while the number is not zero the loop will execute, but I don't know how I could get the number to go back to zero. I'm currently trying to com up with a better while statement. I'm trying to get the program to be able to read any integer and put out each digit as a single number and also out the sum of all the integers. For example: 23947823 would output; 2 3 9 4 7 8 2 3 and also the sum of them.
Last edited on
Topic archived. No new replies allowed.