Click here to Skip to main content
15,912,329 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi guys,

I am having some difficulties creating a loop to get to 1 digit. E.g 999992 does change to 47 and 11, but not to 2 as it should....

Here's my code:
C++
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
	int n, sum=0, total=0;
	cout << "Enter an integer." << endl;
	cin >> n;
	cout << "You have entered: " << n << endl;
	
	while (n > 0) {
	 sum += n % 10;
	 n /= 10;
	}

	cout << "The digitsum is: " << sum << endl;
	
	if (sum < 10)
	 cout << "The total digitsum is: "<< sum << endl;
	else 
	 do {
	  total += sum % 10;
	  sum /= 10;
	  cout << "The total digitsum is: " << total << endl;
	 } while (total < 10);
	
	system("pause");
	return 0;
}

Can anyone help me out here?
Posted
Updated 13-Dec-15 7:32am
v2
Comments
Sergey Alexandrovich Kryukov 13-Dec-15 13:28pm    
Use the debugger.
—SA
Member 12204492 13-Dec-15 13:31pm    
The debugger returns the values 7 and 11 as total digitsum while it should be 2
Sergey Alexandrovich Kryukov 13-Dec-15 13:37pm    
Simply write required number of functions, not just main.
Your algorithm of finding sum of digits works correctly. But then... where do you assign sum to 0?
If your sum was a value in new stack frame, you would not make this mistake.
—SA
Member 10641779 14-Dec-15 5:35am    
change `while (total < 10);` to `while (sum);`

1 solution

Please see my comments to the function. Fair rules tell use: it's enough to locate just first bug, then you should take it into it account and fix it.

Create at least two more functions: one calculating sum of digits, another one representing outer cycle. Your algorithm of finding sum of digits works correctly for the very first time. If you make it a separate function, the variable sum will be initialized to 0 on each call. The rest of the problem will be solved in a trivial way. It's your turn now.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900