Enter a Number and Find Sum of It's Digits (Commented)

22:35 0 Comments A+ a-

Problem:
Write a program that contains a function int sum_of_digits(int) which takes an integer number
as parameter and returns the sum of the digits of that integer number.

For example, when 234 is passed to the function and it returns 9.
Solution:
# include <iostream>
using namespace std;
int sum_of_digits(int); //prototype for function sum_of_digits with parameter int and calculates the sum of digits of integer passed to it as argument
int main()
{
int integer; //integer is the value to be recieved
cout << "Please Enter the Integer : ";
cin >> integer; //input taken in integer variable
cout << "The Sum of the Digits of Integer entered is : " << sum_of_digits(integer) << endl; //sum of digits in the integer variable shown after calling it with argument integer

system("pause");
return 0;
}
int sum_of_digits(int num) //defining of sum_of_digits function
{
int sum = 0; //sum of digits of variable num(integer) intialized with 0
while (num != 0) //loop for finding sum of digits of num until it becomes 0
{
sum = sum + num % 10; //last digit in num added to sum
num = num / 10; //last digit of num removed
}
return sum; //sum of digits returned to main function were it is called

}