Loops, especially for-loops, are subject to two common issues at the problem boundaries (i.e., the beginning and end of the loop). The first error is often called off by one, while the name of the second seems entirely unrelated to programming: the fence post problem.
for (int i = 1; i < 10; i++) |
for (int i = 0; i <= 10; i++) |
(a) | (b) |
for (int i = 1; i <= 10; i++) |
for (int i = 0; i < 10; i++) |
(c) | (d) |
wiktionary.org provides a simple, clear definition of the fence post problem:
If one wants to say "lay a fence post, then a length of fence, then repeat," then a special case must be made for the final fence post. If one wants to say "lay a length of fence, then a fence post, then repeat," then a special case must be made for the initial fence post.
[Downloaded 2019/01/12]
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z |
|
(a) | (b) |
for (char c = 'A'; c <= 'Z'; c++) cout << c << '|'; cout << endl; |
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z| |
(c) | (d) |
for (char c = 'A'; c <= 'Z'; c++) { cout << c; if (c != 'Z') cout << '|'; } cout << endl; |
cout << 'A'; for (char c = 'B'; c <= 'Z'; c++) cout << '|' << c; cout << endl; |
for (char c = 'A'; c < 'Z'; c++) cout << c << '|'; cout << 'Z' << endl; |
(a) | (b) | (c) |
c = 'B'
replaces c = 'A'
, and perform the first output operation before entering the loop.c <= 'Z'
becomes c < 'Z'
and (2) the output removed from the loop is naturally incorporated into an existing output statement. This incorporation notwithstanding, (b) and (c) are generally equivalent in size and complexity.