Pattern

 avatar
unknown
c_cpp
20 days ago
1.0 kB
0
Indexable
#include <iostream>
#include <cmath>

// Function to print the pattern
void printPattern(int size) {
    int center = size / 2;

    for (int row = 0; row < size; ++row) {
        int distanceFromCenter = std::abs(center - row);
        int spacesInRow = size - 2 * (1 + distanceFromCenter);
        int maxSpaceColumnDistance = spacesInRow / 2;

        for (int col = 0; col < size; ++col) {
            int columnDistance = std::abs(center - col);

            if (row == 0 || row == size - 1) {
                std::cout << "*\t";
            } else if (columnDistance > maxSpaceColumnDistance) {
                std::cout << "*\t";
            } else {
                std::cout << " \t";
            }
        }
        std::cout << '\n';
    }
}

int main() {
    int size;
    std::cout << "Enter the size of the pattern: ";
    std::cin >> size;

    // Validate user input
    if (size <= 0 || size%2!=1) {
        std::cerr << "Size must be a positive and odd integer.\n";
        return 1;
    }

    printPattern(size);
    return 0;
}
Leave a Comment