Embercode
✕
C++ PatternsQuick quiz

Pattern debugging

6 questions. Covers Pattern debugging lab.

Questions 1 to 5 of 6

  1. 1. This program should print a diamond for n = 3. It prints 6 rows, and the bottom half repeats the widest row. Which line is the bug? ``cpp for (int i = 1; i <= n; ++i) { std::cout << std::string(n - i, ' ') << std::string(2 * i - 1, '*') << '\n'; } for (int i = n; i >= 1; --i) { std::cout << std::string(n - i, ' ') << std::string(2 * i - 1, '*') << '\n'; } ``
  2. 2. A pyramid for n = 4 should have rows of 1, 3, 5 and 7 stars, with a single star in the middle of each row. This program prints ** as its top row. Which line is the bug? ``cpp for (int i = 1; i <= n; ++i) { std::cout << std::string(n - i, ' ') << std::string(2 * i, '*') << '\n'; } ``
  3. 3. This program should print the top half of a pyramid for n = 4, with rows of 1, 3, 5 and 7 stars. It prints only three rows, and the 7-star row is missing. Which line is the bug? ``cpp for (int i = 1; i < n; ++i) { std::cout << std::string(n - i, ' ') << std::string(2 * i - 1, '*') << '\n'; } ``
  4. 4. Put the five steps of the pattern debugging method in the order you follow them.

    Use the arrows to put the steps in order.

    1. 1.Count the rows and compare the count with the formula.
    2. 2.Read the loop that prints that row.
    3. 3.Find the first row that differs from the expected output.
    4. 4.Write the expected output first, before reading the broken code.
    5. 5.Change one thing, run the program again and compare.
  5. 5. This program prints a diamond for n = 4. Each row ends with | instead of a newline, and the dots stand for spaces. What does it print? ``cpp #include <iostream> #include <string> int main() { const int n = 4; for (int i = 1; i <= n; ++i) { std::cout << std::string(n - i, '.') << std::string(2 * i - 1, '*') << '|'; } for (int i = n - 1; i >= 1; --i) { std::cout << std::string(n - i, '.') << std::string(2 * i - 1, '*') << '|'; } } ``

4 question(s) left on this page.