145k views
5 votes
Use the arr field and mystery () method below.

private int[] arr;

//precondition: arr.length > 0
public void mystery()
{
int s1 = 0;
int s2 = 0;

for (int i = 0; i < arr.length; i++)
{
int num = arr[i];

if ((num > 0) && (num % 2 == 0))
{
s1 += num;
}
else if (num < 0)
{
s2 += num;
}
}

System.out.println(s1);
System.out.println(s2);
}
Which of the following best describes the value of s1 output by the method mystery?

The sum of all values greater than 2 in arr
The sum of all values less than 2 in arr
The sum of all positive values in arr
The sum of all positive odd values in arr
The sum of all positive even values in arr

User Jsibs
by
6.2k points

1 Answer

7 votes

Answer:

The sum of all positive even values in arr

Step-by-step explanation:

We have an array named arr holding int values

Inside the method mystery:

Two variables s1 and s2 are initialized as 0

A for loop is created iterating through the arr array. Inside the loop:

num is set to the ith position of the arr (num will hold the each value in arr)

Then, we have an if statement that checks if num is greater than 0 (if it is positive number) and if num mod 2 is equal to 0 (if it is an even number). If these conditions are satisfied, num will be added to the s1 (cumulative sum). If num is less than 0 (if it is a negative number), num will be added to the s2 (cumulative sum).

When the loop is done, the value of s1 and s2 is printed.

As you can see, s1 holds the sum of positive even values in the arr

User Swapnil Dalvi
by
5.6k points