Sum of digits program using a function – Computer Sir Ki Class

Code Learning #CPP#2189

## Sum of digits program using a function

Writing function sumofdigits() to add the digits in any integer number and then using this function in the main function.

## Learning Objectives

• Writing a function for summing of digits of a number.
• Using the returned value of a function in an intermediate variable in the calling function.
• Advantages of writing a function to avoid creating copy of a variable which is changed while doing loop operations.

## Run Output

``````Input a number : 5678
Sum of Digits of 5678 is 26
``````

## Code Understanding

int sumofdigits(int); //declaration of sumofdigits function prototype

int n,s;
variable n used for input number collection and s for collecting the returned value from sumofdigits function.

cout<<“Input a number : ” ; cin>>n; //Collecting user input

s=sumofdigits(n);
Making a function call to sumofdigits function by passing the actual parameter n which is collected from the user

cout <<“Sum of Digits of “<<n<<” is “<<s;
Outputting the sum appropriately.

int sumofdigits(int n)
The header line of the function definition with the return data type as integer and formal parameter n.

int s=0,rem=0;
Here we need to declare variable to be used in the scope of sumofdigits function only. Variable s is made 0 so that successive sum is added in it.

while(n>0){rem=n%10; s+=rem; n=n/10;}
This is typical while loop we use in successive sum of the digits. Detailed description can be seen in the related post id #2106.

return s;
The sum thus obtained is returned to the calling program.

## Notes

• With these type of functions where the value being input is used is changed while the program code running is not required to be saved in another variable. You may recall that in program at #2106 we were required to save the value entered by user to another variable so that it can be shown later to the user after the loop is complete. Watch the line int nc=n; used for this purpose. So functions do give this kind of advantage as well.

## Common Errors

• The most common error student do is the reversal of > operator to < operator in while loop condition.

Suggested Filename(s): fn-sum-of-digits.cpp

sunmitra| Created: 5-Jan-2018 | Updated: 15-Sep-2018|

×