It looks like you're trying to write a C++ program that:
- Continuously reads integers from the user until
0 is entered.
- For each non-zero integer, calculates the sum of its digits.
- Prints the sum of the digits (but only the last one, due to the logic flaw we'll discuss below).
However, there are a couple of issues with your code:
Issue 1: sum is not accessible outside the while(1) loop
You've declared int sum = 0; inside the outer while loop. This means that sum is recreated on each iteration and its value is lost when the loop iterates again. As a result, cout << sum << endl; will only print the sum of the digits of the last non-zero input number (actually, it won't even do that correctly, see below). If you want to print the sum of digits for each input number, you should move the cout statement inside the outer loop.
Issue 2: Typo in end1
end1 should be endl (ell, not one). endl is a manipulator that inserts a new line and flushes the output buffer.
Issue 3: Printing only the last sum
As mentioned earlier, you're printing sum outside the loop, so you'll only see the result for the last input (which is 0, actually, because the loop breaks when x == 0). Since sum is not updated when x == 0 (the loop breaks before calculating the sum), you'll get garbage output (or zero, in this case, because sum is initialized to 0).
Here's the corrected version of your code:
#include <iostream>
using namespace std;
int main() {
while (1) {
int x;
cin >> x;
if (x == 0) break;
int sum = 0;
int originalX = x; // Store the original value for printing purposes
while (x) {
sum += x % 10;
x /= 10;
}
cout << "Sum of digits of " << originalX << " is: " << sum << endl;
}
return 0;
}
Changes made:
- Moved
cout inside the outer while loop.
- Fixed
end1 typo to endl.
- Stored the original input value
x in originalX to print it along with its sum of digits.
- Improved output message for clarity.
Example use case:
Input:
123
456
789
0
Output:
Sum of digits of 123 is: 6
Sum of digits of 456 is: 15
Sum of digits of 789 is: 24
Now, the program correctly calculates and prints the sum of digits for each non-zero input number.
As a minor suggestion, consider adding some input validation (e.g., checking if cin failed due to invalid input). This will make your program more robust:
if (!(cin >> x)) {
cerr << "Invalid input!" << endl;
cin.clear(); // Clear error flags
cin.ignore(1000, '\n'); // Ignore rest of the line
continue;
}
Insert this check just after cin >> x;. Happy coding!