Program to find the sum of digits of a number using recursion in C++.
Solution
#include <iostream>
using namespace std;
int sumdigit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sumdigit(n / 10));
}
int main()
{
int n,ans;
cout<<"Enter a number ";
cin>>n;
ans = sumdigit(n);
cout << "Sum of digits in "<< n<<" is "<<ans;
return 0;
}
Output :
Enter a number 124 Sum of digits in 124 is 7