Question:
A math class has been studying methods in their computer science course. The students have learned about methods for performing various mathematical operations. The teacher decides to test their understanding of the concepts by giving them an exam question.
The teacher asks the students to write a method called multiplyEvenNumbers that takes in two integers num1 and num2 and returns the product of all the even numbers between num1 and num2, inclusive. If num1 is greater than num2, the method should return -1.
Create the multiplyEvenNumbers method in the class below:
public class MathClassMethods {
public static int multiplyEvenNumbers(int num1, int num2) {
// Your code here
}
public static void main(String[] args) {
int result = multiplyEvenNumbers(2, 10);
System.out.println(result);
}
}
Write the multiplyEvenNumbers method in the provided code and provide the expected output for the given main method.
Answer:
public class MathClassMethods {
public static int multiplyEvenNumbers(int num1, int num2) {
if (num1 > num2) {
return -1;
}
int product = 1;
for (int i = num1; i <= num2; i++) {
if (i % 2 == 0) {
product *= i;
}
}
return product;
}
public static void main(String[] args) {
int result = multiplyEvenNumbers(2, 10);
System.out.println(result);
}
}
Expected Output:
3840
Explanation:
In the multiplyEvenNumbers method:
num1 is greater than num2. If it is, we return -1 as mentioned in the question.product to 1, which will keep track of the product of the even numbers.num1 to num2 (inclusive) using a for loop.i is even by checking if i modulo 2 is equal to 0 (i % 2 == 0).i is even, we update the product variable by multiplying it with i.product.In the main method, we call the multiplyEvenNumbers method with num1 = 2 and num2 = 10. The method computes the product of the even numbers between 2 and 10, inclusive (2, 4, 6, 8, 10), which is 3840. Finally, we print the result using System.out.println.