229k views
2 votes
The following for loop prints the numbers 1 to 20 on one line with a space between.

for (int i = 1; i <= 20; i++)
{
System.out.print(i + " " ); // prints each value of i followed by a space on one line
}

Question

Consider the for loop example above. Assume you want to adjust the loop to print only the even values from 1 and 20. What must the loop elements - counter initialization, conditional statement, and counter modification - be set to in order to accomplish the goal.

Review all options listed below carefully. You MUST select 3 answers; one for each element/category:

Counter initialization
Conditional statement
Counter modification
a. int i = 0;
b. int i = 1;
c. int i = 2;
d. i < 20;
e. i <= 20;
f. i > 20;
g. i++;
h. i+=1-;
i. i+=2;

User Jgmjgm
by
5.5k points

1 Answer

4 votes

Answer:

Counter initialization:
\verb!int i = 2!.

Conditional statement:
\verb!i <= 20!.

Counter modification:
\verb!i += 2!.

Explanation:

In the current Java for-loop in this question:

  • The counter initialization statement
    \verb!int i = 1! in this for-loop would initialize the counter variable to integer
    1.
  • The conditional statement
    \verb!i <= 20! holds as long as the counter is less than or equal to
    20. Thus, the largest possible value for the counter would be
    20\!.
  • The counter modification statement
    \verb!i++! is equivalent to
    \verb!i += 1!. This statement would add
    1 to the value of the counter in each iteration.

The even integers between
1 and
20 includes
2,\, 4,\, \dots,\, 20. It would be necessary to add
2 each time to get to the next number.

Since the list of even integers starts at
2, it would be necessary to initialize the counter variable to
2\! rather than
1. Thus, replace the counter initialization statement
\verb!int i = 1! with
\verb!int i = 2!.

The maximum integer that this loop should print is still
20. Thus, the conditional statement
\verb!i <= 20! does not need to be changed.

The for-loop should add
2 to the counter each time to get to the next even integer. Thus, the counter modification statement
\verb!i++! (or equivalently,
\verb!i += 1!) should be replaced with
\verb!i += 2!.

Overall, the for-loop should be:


\begin{aligned}&amp; \verb!for (int i = 2; i <= 20; i += 2) {!\\ &amp;\quad \verb!System.out.print(i +.

User HeDinges
by
5.4k points