Embercode
✕
C++ LoopsQuick quiz

Iteration forms

7 questions. Covers Sentinel loops.

Questions 1 to 5 of 7

  1. 1. What does this program print? ``cpp #include <iostream> #include <vector> int main() { std::vector<int> v = {1, 2, 3}; for (int x : v) { x *= 2; } for (auto& x : v) { x += 10; } for (int x : v) { std::cout << x << ' '; } std::cout << '\n'; } ``
  2. 2. The program below reads numbers from standard input. The input is 4, then 6, then 9, then -1, each on its own line. What does it print? ``cpp #include <iostream> int main() { const int sentinel = -1; int x = 0; int total = 0; std::cin >> x; while (x != sentinel) { total += x; std::cin >> x; } std::cout << total << '\n'; } ``
  3. 3. The program below has a bug. What is it? ``cpp #include <iostream> int main() { int arr[] = {1, 2, 3}; int* p = arr; for (int x : p) { std::cout << x << '\n'; } } ``
  4. 4. The input is 5, then 7, then -1. The program prints 11, but the correct total is 12. What is the bug? ``cpp #include <iostream> int main() { const int sentinel = -1; int score = 0; int total = 0; do { std::cin >> score; total += score; } while (score != sentinel); std::cout << "total: " << total << '\n'; } ``
  5. 5. In a sentinel loop that divides an integer total by an integer count, what happens if the very first value read is the sentinel and the count check is missing?

5 question(s) left on this page.