Ask Question
18 December, 20:10

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

+3
Answers (2)
  1. 18 December, 21:19
    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. 18 December, 22:26
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers