C++ Online Compiler
Example: Sum of Individual Digits of a Positive Integer in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Individual Digits of a Positive Integer #include <iostream> using namespace std; int main() { int number; int sum = 0; int digit; // Step 1: Prompt user for input cout << "Enter a positive integer: "; cin >> number; // Step 2: Handle non-positive input (optional but good practice) if (number < 0) { cout << "Please enter a positive integer." << endl; return 1; // Indicate an error } // Step 3: Iterate to sum digits int originalNumber = number; // Store original for output message // Loop continues as long as 'number' is greater than 0 while (number > 0) { // Extract the last digit using the modulo operator digit = number % 10; // Add the extracted digit to the sum sum += digit; // Remove the last digit from the number using integer division number /= 10; } // Step 4: Display the result cout << "The sum of digits of " << originalNumber << " is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS