C++ Online Compiler
Example: Sum of Digits - Recursive Method in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Digits - Recursive Method #include <iostream> using namespace std; // Recursive function to calculate sum of digits int sumDigitsRecursive(int n) { // Base Case: If number is 0, sum is 0 if (n == 0) { return 0; } // Recursive Step: Add the last digit to the sum of the remaining digits return (n % 10) + sumDigitsRecursive(n / 10); } int main() { int number; // Step 1: Prompt user for input cout << "Enter an integer number: "; cin >> number; // Step 2: Handle negative numbers by taking absolute value before calling recursive function int absoluteNumber = number; if (absoluteNumber < 0) { absoluteNumber = -absoluteNumber; } // Step 3: Call the recursive function int sum = sumDigitsRecursive(absoluteNumber); // Step 4: Display the result cout << "The sum of the digits of " << number << " is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS