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.