Ask Question
20 July, 17:06

unsigned int SumOfDigits (unsigned int n) Description: Develop a function that takes a non-negative integer n as a parameter and returns a non-negative integer containing the sum of n's digits. For example, if the input parameter n was 17239 then the output of this function should be 1 + 7 + 2 + 3 + 9 = 22

+4
Answers (1)
  1. 20 July, 21:03
    0
    The solution code is written in C++.

    unsigned int SumOfDigits (int n) { int sum = 0; sum + = n % 10; n = n / 10; while (n! = 0) { sum + = n % 10; n = n / 10; } return sum; }

    Explanation:

    Firstly, define a function with name SumOfDigits () that take one input integer, n and return an unsigned summation integer (Line 1). Next, we declare a variable sum to hold the value of summation of all the integer digits. Let's initialize it with zero (Line 2).

    We can get the first digit from the integer by calculating the remainder of n after dividing it by 10 using modulus operator (%) and the remainder obtained is added to the sum variable (Line 3). Next, we divide the integer n by 10 (Line 4). This will discard the last digit of integer n (from the right).

    We just need to repeat the process from Line 3-4 using a while loop so long as the current integer n is not zero (Line 6-8). We shall be able to take out the individual digit and add it to variable sum.

    At the end, return the sum as output (Line 11).
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “unsigned int SumOfDigits (unsigned int n) Description: Develop a function that takes a non-negative integer n as a parameter and returns a ...” in 📘 Engineering if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers