C++ Online Compiler
Example: Sum of Digits (Iterative) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Digits (Iterative) #include <iostream> using namespace std; int main() { int number; int sum = 0; // Step 1: Prompt the user to enter a number cout << "Enter a number: "; cin >> number; // Step 2: Store the original number for display int originalNumber = number; // Step 3: Loop while the number is greater than 0 while (number > 0) { // Step 3a: Get the last digit of the number int digit = number % 10; // Step 3b: Add the digit to the sum sum += digit; // Step 3c: Remove the last digit from the number number /= 10; // Equivalent to number = number / 10; } // Step 4: Display the result cout << "The sum of digits of " << originalNumber << " is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS