175k views
0 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 2 9 1 0 7 or 19. For negative numbers, return the same value that would result if the number were positive. For example, digitSum(-456) returns 4 5 6 or 15. The call digitSum(0) returns 0.

User Neigaard
by
5.2k points

1 Answer

4 votes

Answer:

The cpp program for the scenario is given below.

#include <iostream>

using namespace std;

// method returning sum of all digits in the integer parameter

int digitSum(int n)

{

// variable to hold sum of all digits in the integer parameter

int sum=0;

if(n == 0)

return 0;

else

{

// for negative parameter, consider positive value of the number

if(n<0)

n = abs(n);

// loop to calculate sum till number is greater than 0

do{

sum = sum + (n%10);

n = n/10;

}while(n>0);

}

// sum of all digits in the integer parameter is returned

return sum;

}

int main()

{

// method is called by passing an integer parameter

cout<<"The sum of the digits is "<<digitSum(-14501)<<endl;

return 0;

}

OUTPUT

The sum of the digits is 11

Step-by-step explanation:

The program works as described below.

1. The method, digitSum(), is defined as having return type as integer and taking input one integer parameter.

int digitSum(int n)

{

}

2. An integer variable, sum, is declared and initialized to 0.

int sum=0;

3. If the input parameter is 0, 0 is returned.

4. If the input parameter is negative, abs() method is used to remove the negative sign.

abs(n);

5. Inside the do-while loop, the sum of all the digits of the input parameter is computed.

do{

sum = sum + (n%10);

n = n/10;

}while(n>0);

6. The digits of the input parameter are obtained by the modulus of n, and added to the variable, sum.

7. Then, n is modified and divided by 10.

8. The digits are obtained using modulus operator on n, and added to the variable, sum till all digits have been added.

9. The loop continues till the value of n is greater than 0.

10. The variable, sum, holding the sum of all digits of the input parameter, n, is returned.

11. The main() method calls the digitSum() method.

12. The program ends with the return statement.

User Timger
by
5.6k points