Sum of digits
#include <bits/stdc++.h>
using namespace std ;
int sum(int n){
//Base case
if (n==0) return 0;
//Recursive case
int smallAns = sum(n/10);
//Calculation
int last_digit = n%10 ;
return smallAns + last_digit ;
}
int main (){
int n ;
cin >> n ;
cout << sum(n) << '\n';
return 0;
}
Comments
Post a Comment