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:
main method, an integer num is assigned the value -123 and a boolean positive is assigned the value true.sumOfDigits method is then called with num and positive as arguments and the returned value is stored in the variable sum.sumOfDigits method, a variable sum is initialized to 0.num is negative and positive is true, the absolute value of num is taken by changing its sign to positive using -num.num is not equal to 0.num is obtained using num % 10 and added to the sum.num is then updated by removing the rightmost digit using num /= 10.num are added to the sum.sum is returned as the result.main method, the value of sum is printed on the console using System.out.println along with an appropriate message.