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 E2010 · EasyPatterns & output

A Diamond of Digits

National Olympiad — Regional round (2010 season)

Submission name: rhomb.cpp

Problem summary

Print a diamond of 2N − 1 rows. A row of size k begins with N − k spaces and contains digits k down to 1 and then 2 up to k. Row sizes rise from 1 to N and then fall back to 1.

Input

An integer N.

Output

The diamond, with no spaces between digits and no blank lines before it.

Constraints

2 ≤ N ≤ 9.

Worked example

An independently prepared example for this explanation.

Input

3

Output

  1
 212
32123
 212
  1

Solution analysis

  1. For row index r from 1 through 2N − 1, choose size k = min(r, 2N − r). This produces the increasing and decreasing halves without duplicating the middle row.
  2. Print N − k leading spaces, then the descending digits k … 1 and ascending digits 2 … k. Starting the second loop at 2 keeps the central 1 unique.
  3. For N = 3 the sizes are 1, 2, 3, 2, 1. The middle row has no leading spaces and reads 32123.

Why it works

The size formula gives exactly the required sequence of row sizes. Each row has the prescribed indentation and symmetric digits centered on one 1. Therefore all rows form the specified diamond.

Complexity: O(N²) time to print Θ(N²) characters and O(1) extra space.

Watch out. Do not repeat the central 1 or the widest row. Leading spaces matter; trailing spaces are unnecessary.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    int n;
    cin >> n;
    for (int row = 1; row < 2 * n; row++) {
        // Rise to the widest row once, then mirror the row sizes.
        int size = min(row, 2 * n - row);
        cout << string(n - size, ' ');
        for (int digit = size; digit >= 1; digit--) {
            cout << digit;
        }
        for (int digit = 2; digit <= size; digit++) {
            cout << digit;
        }
        cout << '\n';
    }
}

Source: Arena Olimpiici ↗