Problem of the Day
Thursday, November 5, 2026
Problem:
A for loop is written with the header
for (int i = a; i < b; i++)
... where int variables a and b have been assigned values, with a<=b. Which characteristics below correctly describe this loop?
| initial value of i | final value of i | number of times the loop repeats | |
| a. | a | b | b - a |
| b. | a | b - 1 | b - a + 1 |
| c. | a | b | b - a + 1 |
| d. | a | b - 1 | b - a |
The correct answer is d. Although for loops are one of the most useful looping strategies and their behavior is well known, it's common for issues to arise when writing them. In the case of a loop executing one time too many or one time to few, the error is called an "off-by-one" error.
Note, too, that Java allows an index variable (such as i in this example) to be altered during the execution of the body of the loop. For most programmers, this behavior is unexpected and to be avoided.