Embercode
✕
C++ LoopsQuick quiz

Off-by-one check

6 questions. Covers Half-open ranges.

Questions 1 to 5 of 6

  1. 1. This code should print the three names at positions 2, 3 and 4 (Chen, Dara and Eli). Which statement is correct? ``cpp #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> names = {"Ada", "Ben", "Chen", "Dara", "Eli", "Fay", "Gus", "Hana"}; for (int i = 2; i < 4; ++i) { cout << names[i] << "\n"; } return 0; } ``
  2. 2. A calendar stores each meeting as a half-open range, so 9 to 10 ends at 10 and 10 to 11 starts at 10. This program checks for a clash. Which statement about it is correct? ``cpp #include <iostream> using namespace std; struct Meeting { int start; int end; }; bool overlaps_closed(Meeting a, Meeting b) { return a.start <= b.end && b.start <= a.end; } int main() { Meeting first = {9, 10}; Meeting second = {10, 11}; cout << "clash: " << overlaps_closed(first, second) << "\n"; return 0; } ``
  3. 3. This code should print each of the 8 names once, in groups of three. Which statement is correct? ``cpp #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> names = {"Ada", "Ben", "Chen", "Dara", "Eli", "Fay", "Gus", "Hana"}; int n = static_cast<int>(names.size()); for (int lo = 0; lo < n; lo += 3) { int hi = min(lo + 3, n - 1); for (int i = lo; i < hi; ++i) cout << names[i] << " "; cout << "\n"; } return 0; } ``
  4. 4. What does this program print? Each group is one line. ``cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { vector<int> v = {1, 2, 3, 4, 5, 6, 7}; int n = static_cast<int>(v.size()); for (int lo = 0; lo < n; lo += 3) { int hi = min(lo + 3, n); cout << "[" << lo << ", " << hi << ") " << hi - lo << "\n"; } return 0; } ``
  5. 5. What does this program print? Each number is on its own line. ``cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { vector<int> v = {1, 3, 3, 8, 9}; cout << lower_bound(v.begin(), v.end(), 3) - v.begin() << "\n"; cout << lower_bound(v.begin(), v.end(), 10) - v.begin() << "\n"; return 0; } ``

5 question(s) left on this page.