U-Shaped String Formatting and Hourglass Pattern Printing

U-Shaped String Output

Given a string of length N, display it in a U-shape formation. Let n1 represent the left vertical column, n3 represent the right vertical column, and n2 represent the bottom horizontal row. The constraint requires n1 = n3 = max { k | k <= n2 for all 3 <= n2 <= N } and n1 + n2 + n3 - 2 = N.

For example, with input "Helloworld!" (N=11), the result is: n1="hell", n2="lowor", n3="rld!".

Solution Approach

From the equation n1 + n2 + n3 - 2 = N and n1 = n3, we derive that n1 = n3 = n2 = (N+2)/3. This maximizes the vertical sides while satisfying the constraint.

To output the pattern:

  1. For each of the first (side - 1) rows, output the character at position i, then (len - 2*side) spaces, then the character at position (len - 1 - i)
  2. Output the remaining characters from position (side - 1) onwards for the bottom row

Implementation

#include <iostream>
#include <cstring>
using namespace std;

const int MAX_SIZE = 100;

int main() {
    char s[MAX_SIZE];
    while (cin >> s) {
        int length = strlen(s);
        int height = (length + 2) / 3;
        int spaces = length - 2 * height;
        
        for (int row = 0; row < height - 1; ++row) {
            cout << s[row];
            for (int col = 0; col < spaces; ++col)
                cout << " ";
            cout << s[length - 1 - row] << endl;
        }
        
        for (int i = height - 1; i < height + spaces; ++i)
            cout << s[i];
    }
    return 0;
}

Hourglass Pattern Generation

Print a symmetric hourglass pattern using asterisks based on the input size n.

The pattern consists of two parts:

  1. Upper triangle: rows 0 to n-1, where each row i contains i leading spaces followed by (n-i) asterisks
  2. Lower triangle: rows 1 to n-1, where each row i contains (n-i-1) leading spaces followed by (i+1) asterisks

Implementation

#include <iostream>
using namespace std;

int main() {
    int size;
    while (cin >> size) {
        for (int row = 0; row < size; ++row) {
            for (int col = 0; col < row; ++col)
                cout << " ";
            for (int col = 0; col < size - row; ++col)
                cout << "* ";
            cout << endl;
        }
        for (int row = 1; row < size; ++row) {
            for (int col = 0; col < size - row - 1; ++col)
                cout << " ";
            for (int col = 0; col < row + 1; ++col)
                cout << "* ";
            cout << endl;
        }
    }
    return 0;
}

Tags: C++ string processing Pattern Printing U-Shaped Output Hourglass Pattern

Posted on Tue, 08 Sep 2026 16:51:42 +0000 by greekhand