Ask Question
17 September, 14:41

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

+2
Answers (2)
  1. 17 September, 17:30
    0
    We first look at the loop:

    i=0 to i
    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
    (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.
  2. 17 September, 17:57
    0
    a.

    Explanation:

    Suppose n=7, then the loop will be executed for i=0, 2, 4 and 6, so 4 times.

    (int) ((7+1) / 2) = 4.

    Suppose n=6, then the loop will be executed for i=0, 2 and 4, so 3 times.

    (int) ((6+1) / 2) = 3.

    a. is the only formula that works.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Consider the following loop, where n is some positive integer. for (int i = 0; i < n; i + = 2) { if ( / * condition to test * / ) { / * ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers