Write a recursive function that returns the sum of the digits of a given integer.

PROBLEM
:-
Sum of digits (recursive)
Send Feedback

Write a recursive function that returns the sum of the digits of a given integer.

Input format :
Integer N
Output format :
Sum of digits of N
Constraints :
0 <= N <= 10^9
Sample Input 1 :
12345
Sample Output 1 :
15
Sample Input 2 :
9
Sample Output 2 :
9
SOLUTION:-
#include <iostream>
using namespace std;
int sumOfDigits(int n) {
    // Write your code here
 if(n<10)
 {
     if(n==0)
     {
         return 0;
     }
     else
         return n;
 }
    
    int d=n%10;
    return d+sumOfDigits(n/10);
    
}




int main() {
   int n;
   cin >> n;
   cout << sumOfDigits(n) << endl;
}

Newest
Previous
Next Post »

2 comments

Click here for comments

If you have any doubts then please let me know... ConversionConversion EmoticonEmoticon