132k views
3 votes
Consider the following code segment.

int n = 6;
for (int i = 1; i < n; i = i + 2) // Line 2
{
System.out.print(i + " ");
}
Which of the following best explains how changing i < n to i <= n in line 2 will change the result?
A. An additional value will be printed because the for loop will iterate one additional time.
B. One fewer value will be printed because the for loop will iterate one fewer time.
C. There will be no change to the program output because the loop will iterate the same number of times.
D. An infinite loop will occur because the loop condition will never be false.
E. The body of the loop will not execute at all because the loop condition will initially be false.

User SevenDays
by
8.3k points

1 Answer

4 votes

Final answer:

If the loop condition i < n is changed to i <= n, an additional value will be printed because the for loop will iterate one additional time.

Step-by-step explanation:

If the loop condition i < n is changed to i <= n in line 2, an additional value will be printed because the for loop will iterate one additional time.

For example, if n = 6, the loop will iterate as follows:

  • i = 1, 1 <= 6, print 1
  • i = 3, 3 <= 6, print 3
  • i = 5, 5 <= 6, print 5
  • i = 7, 7 is not less than or equal to 6, exit the loop

So, changing the loop condition will result in an additional value being printed.

User Sarah Messer
by
7.5k points