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;

Respuesta :

Answer:

Counter initialization: [tex]\verb!int i = 2![/tex].

Conditional statement: [tex]\verb!i <= 20![/tex].

Counter modification: [tex]\verb!i += 2![/tex].

Step-by-step explanation:

In the current Java for-loop in this question:

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

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

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

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

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

Overall, the for-loop should be:

[tex]\begin{aligned}& \verb!for (int i = 2; i <= 20; i += 2) {!\\ &\quad \verb!System.out.print(i + " ");! \\ &\verb!}!\end{aligned}[/tex].