280,523 views
35 votes
35 votes
write a method called digitsum that accepts an integer as a parameter and returns the sum of the digits of that number. for example, the call digitsum(29107) returns or 19 . for negative numbers, return the same value that would result if the number were positive. for example, digitsum(-456) returns or 15 . the call digitsum(0) returns 0 .

User Tim Sparkles
by
3.0k points

1 Answer

16 votes
16 votes

C++:

#include <iostream>

int digitsum(int n) {

if(n==0) return 0;

return (n%10)+digitsum(n/10);

}

int main(int argc, char* argv[]) {

std::cout << "Enter a number to calculate: ";

int x; std::cin>>x;

if(x<0) std::cout << "Sum is: " << digitsum(x*(-1));

else std::cout << "Sum is: " << digitsum(x);

return 0;

}

Python:

def digitsum(n):

if(n==0): return 0

return int((n%10)+digitsum(n/10))

x = int(input("Enter a number to calculate: "))

if(x<0):

print("Sum is:",digitsum(x*(-1)))

else:

print("Sum is:",digitsum(x))

User Mukarram Khalid
by
2.8k points