Post

Created by @nathanedwards
 at November 1st 2023, 4:40:06 pm.

AP Computer Science Exam Question

Question:

Write a Java method called sumOfDigits that takes an integer as a parameter and returns the sum of its digits.

The signature of the method is as follows:

public static int sumOfDigits(int num)

Example:

sumOfDigits(12345) returns 15

Explanation:

The given number is 12345.

The sum of its digits is 1 + 2 + 3 + 4 + 5 = 15.

Therefore, the method should return 15.

- Note: Assumption is that the input number will always be positive.

Your Task:

Implement the provided method sumOfDigits in Java, using loops and arithmetic operations, to compute the sum of the digits of a given number.

Solution:

Here is one possible solution for the sumOfDigits method:

public static int sumOfDigits(int num) {
    int sum = 0;
    
    // Iterate through each digit of the number
    while (num != 0) {
        // Get the last digit of the number
        int digit = num % 10;
        
        // Add the digit to the sum
        sum += digit;
        
        // Update the number by removing the last digit
        num /= 10;
    }
    
    // Return the final sum of the digits
    return sum;
}

Let's walk through the code step-by-step:

  1. Initialize a variable sum to store the sum of digits, and set it to 0.
  2. Use a while loop to iterate through each digit of the number. The loop continues as long as the number is not equal to 0.
  3. Inside the loop, compute the last digit of the number by taking the modulus (%) of the number with 10.
  4. Add the digit to the sum by using the assignment operator (+=).
  5. Update the number by dividing it by 10, which removes the last digit.
  6. Repeat steps 3-5 until all the digits of the number have been processed.
  7. After the loop, the variable sum will contain the sum of all the digits.
  8. Return the sum as the final result.

By implementing this method, we can successfully calculate the sum of digits for any positive integer.


Make sure to test your sumOfDigits method with various input values to ensure it behaves as expected.