cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2011 · EasyPatterns & output

A Character House

National Olympiad — National round (2011 season)

Submission name: house.cpp

Problem summary

Print a centered house. The roof has h rows: row r contains r forward slashes followed by r backslashes. Below it, print a filled rectangle of b rows and 2b equals signs per row. Center the rectangle under the roof.

Input

Two integers h and b.

Output

The house with no blank lines or trailing spaces. The widest roof row starts at column 1.

Constraints

2 < b < h < 40.

Worked example

An independently prepared example for this explanation.

Input

6 3

Output

     /\
    //\\
   ///\\\
  ////\\\\
 /////\\\\\
//////\\\\\\
   ======
   ======
   ======

Solution analysis

  1. The roof’s final width is 2h. Row r has width 2r, so h − r spaces place it in the center.
  2. The rectangular body has width 2b and height b. Its indentation is (2h − 2b)/2 = h − b spaces. Use repeated-character strings to express each part directly.
  3. For h = 6 and b = 3, roof indentations are 5, 4, 3, 2, 1, 0. Each body row has three leading spaces and six equals signs, centered beneath the 12-character roof base.

Why it works

Each roof row has exactly r of each slash and the indentation centers its 2r characters within width 2h. Each of the b body rows has width 2b and the same center. No other characters are printed, so the resulting house has exactly the required dimensions and alignment.

Complexity: O(h² + b²) time to print the characters and O(h + b) space for temporary strings.

Watch out. Escape the backslash in a C++ character literal. Rectangle height is b, width is 2b. Do not add trailing spaces.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
#include <string>
using namespace std;
int main() {
    int roofHeight, bodyHeight;
    cin >> roofHeight >> bodyHeight;
    for (int row = 1; row <= roofHeight; row++) {
        // Indent each row so its slash halves share the same center.
        cout << string(roofHeight - row, ' ');
        cout << string(row, '/');
        cout << string(row, '\\') << '\n';
    }
    for (int row = 0; row < bodyHeight; row++) {
        cout << string(roofHeight - bodyHeight, ' ');
        cout << string(2 * bodyHeight, '=') << '\n';
    }
}

Source: Arena Olimpiici ↗