C++ Online Compiler
Example: Sum of Digits (Recursive) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Digits (Recursive) #include <iostream> using namespace std; // Function to calculate the sum of digits recursively int sumOfDigitsRecursive(int n) { // Step 1: Base Case - If the number is 0, the sum is 0 if (n == 0) { return 0; } // Step 2: Recursive Step - Add the last digit to the sum of remaining digits else { return (n % 10) + sumOfDigitsRecursive(n / 10); } } int main() { int number; // Step 3: Prompt the user to enter a number cout << "Enter a number: "; cin >> number; // Step 4: Call the recursive function int sum = sumOfDigitsRecursive(number); // Step 5: Display the result cout << "The sum of digits of " << number << " is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS