C++ Online Compiler
Example: Sum of Digits - Iterative Method in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Digits - Iterative Method #include <iostream> using namespace std; int main() { int number; int sum = 0; // Step 1: Prompt user for input cout << "Enter an integer number: "; cin >> number; // Step 2: Handle negative numbers by converting to positive int tempNumber = number; if (tempNumber < 0) { tempNumber = -tempNumber; } // Step 3: Iterate using a while loop to sum digits while (tempNumber > 0) { int digit = tempNumber % 10; // Get the last digit sum += digit; // Add digit to sum tempNumber /= 10; // Remove the last digit } // Step 4: Display the result cout << "The sum of the digits of " << number << " is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS