Method sumDigits takes a non-negative integer and returns the sum of its base-10 digits. For example, sumDigits (1234) returns $1 + 2 + 3 + 4 = 10$. Note that it is easy to split an integer into two smaller pieces by dividing by 10 (e.g., 1234/10 = 123, and 1234 % 10 = 4).

 Method sumDigits takes a non-negative integer and returns the sum of its base-10 digits. For example, sumDigits (1234) returns $1 + 2 + 3 + 4 = 10$. Note that it is easy to split an integer into two smaller pieces by dividing by 10 (e.g., 1234/10 = 123, and 1234 % 10 = 4).



#include<iostream>

using namespace std;

 

int sum_of_digit(int num)  

{  

    if (num == 0)

{

    return 0;  

}  

    return (num % 10 + sum_of_digit(num / 10));  

}  

  

int main()  

{  

    int num;

    int result;

cout<<"Enter Number  =  ";

    cin>>num;

    result = sum_of_digit(num);

cout << "Sum of digits 1 + 2 + 3 + ... + "<< num  <<" is "<<"  =   "<<result << endl;  

    return 0;  

}  

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.