Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which of the following for loops covers the same range of values of i as for (i = 0; i < n; i++)?

  • A.for (i = n; i>0; i--)
  • B.for (i = n; i>=0; i--)
  • C.for (i = n-1; i>0; i--)
  • D.for (i = n-1; i>-1; i--)

Answer: D

Correct answer: for (i = n-1; i>-1; i--)

for (i = 0; i < n; i++) visits 0 to n-1. Running the same range backwards means starting at n-1 and continuing while i is still at least 0 - that is, while i > -1. The alternatives either start at n, which is out of range, or stop at i > 0, which misses the element at index 0.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.