209k views
3 votes
Consider the following loop, where n is some positive integer.

for (int i = 0; i < n; i += 2) {
if (/* condition to test */) {
/* perform some action */
}
}
In terms of n, which Java expression represents the maximum number of times that /* perform some action */ could be executed?
a. (n + 1) / 2
b. n / 2
c. (n - 1) / 2
d. n
e. n-1

User Sumitya
by
6.4k points

1 Answer

5 votes

Step-by-step explanation:

We first look at the loop:

i=0 to i<n; i+=2

means

i goes from 0 to n-1 in steps of 2.

For the step of 2, we conclude immediately that the value of n must be divided by two, whether we add or subtract constants from it.

As long as n>=0, the number of times execution proceeds is (n-1)/2 (because i<n). To this we add the case i=0, which is always executed, which gives

(i-1)/2 + 1 = (i+1)/2.

We still need to check at least two values of n (= odd and even).

n=7, execution cases are 0,2,4,6 totaling 4. (7+1)/2 = 4, good!

n=8, execution cases are 0,2,4,6 again totalling 4. ((8+1)/2) = 9/2 = 4 (integer division truncates) So again it is correct.

So the answer choice is (n+1)/2.

User EsmaeelE
by
5.2k points