Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive function, sumDigits, that takes an integer as a parameter and

ID: 3708573 • Letter: W

Question

Write a recursive function, sumDigits, that takes an integer as a parameter and returns the sum of the digits of the integer.

please use the templates below to make the program. ( C++ )

functions.cpp

#include <iostream>

using namespace std;

inline void sumDigits(long long& sum, long long num)
{
//checkign base condtion here

if(num == 0)

return ;

else

{ //adding the last digit to the sum

sum += num%10;

num /= 10; //removing the last digit from num

sumDigits(sum, num); //calling recursively

}

______________________________________________________________________

main.cpp

#include <iostream>
#include "functions.cpp"

using namespace std;

int main()
{
long long num = 930567829100185;
long long sum = 0;

sumDigits(sum, num);

cout << "The sum of the digits of " << num << " is: " << sum << endl;

return 0;
}

Explanation / Answer

#include <iostream>

using namespace std;
long long sumDigits(long long& sum,long long num) {
if(num <= 0) {
return 0;
} else {
sum = sum + (num % 10);
return sumDigits(sum,num/10);
}
}
int main()
{
long long num = 930567829100185;
long long sum = 0;

sumDigits(sum,num);

cout << "The sum of the digits of " << num << " is: " << sum << endl;

return 0;
}

Output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote