SCE

Recursive function that find the sum of digits in a integer using C++

###### Posted by Samath

Last Updated:
December 24, 2014

Write a function that computes the sum of the digits in an integer.

Use the following function header:

int sumDigits(long n)

For example, sumDigits(234) returns 2 + 3 + 4 = 9.

Develop a program that prompts the user to enter any integer and display the sum of all its digits.

Solution:

#include <iostream> using namespace std; int sumDigits(int num); int main(int argc, char *argv[]) { cout<<"Result: "<<sumDigits(234)<<"\n"; return 0; } int sumDigits(int num) { if(num == 0) { return num; } else { return sumDigits(num/10) + (num%10); } }