Back to questions
JuniorTheoryCommon
What does the program print?
#include <iostream>
int main() {
int a = 0;
for (int i = 0; i <= 5; ++i) { ++a; }
int b = 0;
for (int i = 1; i < 5; ++i) { ++b; }
std::cout << a << ' ' << b;
}6 4
- Expecting
5 4:<=letsireach the bound, so the first loop runs for0,1, …5, six values in all, not five. - Expecting
6 5: the second loop starts at1, soitakes only the values1to4, and the body runs four times.
- How would you write a
forloop whose body runs exactlyntimes? - What goes wrong if a loop like the first one reads the elements of a 5-element array?