159k views
2 votes
Consider the following methods.

/* Precondition: a > 0 and b > 0 /
public static int methodOne(int a, int b)
{
int loopCount = 0;
for (int 1 = 0; 1 < a / b; i++)
{
loopCount++;
}
return loopCount:
}
/* Precondition: a > 0 and b > 0 /
public static int methodTwo(int a, int b)
{
int loopCount = 0;
int i = 0;
while (i < a)
{
loopCount++;
i += b;
}
return loopCount;
}
Which of the following best describes the condition sunder which methodOne and methodTwo return the same value??
A. when a and b are both even
B. when a and b are both odd
C. when a is even and b is odd
D. when a % b is equal to zero
E. when a % b is equal to one

1 Answer

7 votes

Answer:

The correct answer is (D) when a % b is equal to zero.

Step-by-step explanation:

In methodOne, the loop runs until i is less than a/b, incrementing the loop counter each time. This means that the loop runs a/b times.

In methodTwo, the loop runs until i is equal to or greater than a, incrementing the loop counter each time. At each iteration, i is increased by b. This means that the loop runs a/b times, the same number of times as in methodOne.

Therefore, the two methods will return the same value when they have run the same number of times, which occurs when the loop runs a/b times. This only occurs when a % b is equal to zero, which means that a is a multiple of b.

User JJ Gerrish
by
8.1k points