Post

Created by @nathanedwards
 at November 1st 2023, 1:57:24 pm.

Question:

Consider the following method definition:

public static int sumOfDigits(int num, boolean positive) {
    int sum = 0;
    
    if (num < 0 && positive) {
        num = -num;
    }
    
    while (num != 0) {
        sum += num % 10;
        num /= 10;
    }
    
    return sum;
}

The sumOfDigits method takes an integer num as its first parameter and a boolean positive as its second parameter. It calculates the sum of the digits of num and returns it. However, if the positive parameter is true and num is negative, it considers the absolute value of num and calculates the sum of its digits.

For example, calling sumOfDigits(-123, true) would return 6 because the sum of the digits of 123 is 1 + 2 + 3 = 6.

You are given the task to write the code for the main method that calls the sumOfDigits method with appropriate arguments and prints the sum of the digits.

Write the code for the main method that calls the sumOfDigits method with the appropriate arguments and displays the sum of the digits.

Your Answer:

public class Main {
    public static void main(String[] args) {
        int num = -123;
        boolean positive = true;

        int sum = sumOfDigits(num, positive);
        System.out.println("Sum of digits: " + sum);
    }
    
    public static int sumOfDigits(int num, boolean positive) {
        int sum = 0;
    
        if (num < 0 && positive) {
            num = -num;
        }
    
        while (num != 0) {
            sum += num % 10;
            num /= 10;
        }
    
        return sum;
    }
}

Explanation:

  1. In the main method, an integer num is assigned the value -123 and a boolean positive is assigned the value true.
  2. sumOfDigits method is then called with num and positive as arguments and the returned value is stored in the variable sum.
  3. Inside the sumOfDigits method, a variable sum is initialized to 0.
  4. If the num is negative and positive is true, the absolute value of num is taken by changing its sign to positive using -num.
  5. A while loop is used to iterate until num is not equal to 0.
  6. In each iteration, the rightmost digit of num is obtained using num % 10 and added to the sum.
  7. The value of num is then updated by removing the rightmost digit using num /= 10.
  8. The process continues until all digits of num are added to the sum.
  9. Finally, the sum is returned as the result.
  10. In the main method, the value of sum is printed on the console using System.out.println along with an appropriate message.