Print Hollow Square Pattern

Print Hollow Square Pattern

Medium C++ Pattern Printing 38 views
Explanation Complexity

Problem Statement

Print square with only border stars.
Real Life: Understanding boundary detection.

Input Format

An integer n (size of the square).

Output Format

Square pattern using *
Only border stars, inside is empty.

Example

5
*****
*   *
*   *
*   *
*****

Constraints

• n ≥ 1

• Use loops only

Concept Explanation

Only the boundary of the square has stars.
Inner positions contain spaces.
This helps understand boundary detection using row and column indexes.

Step-by-Step Explanation

1.Take input n.

2.Loop rows from 1 to n.

3.Inside each row, loop columns from 1 to n.

4.Print * when:

• Row is 1 or n

• OR column is 1 or n

5.Otherwise, print space " ".

6.After each row, move to next line.

Concept Explanation

Only the boundary of the square has stars.
Inner positions contain spaces.
This helps understand boundary detection using row and column indexes.

Step-by-Step Explanation

1.Take input n.

2.Loop rows from 1 to n.

3.Inside each row, loop columns from 1 to n.

4.Print * when:

• Row is 1 or n

• OR column is 1 or n

5.Otherwise, print space " ".

6.After each row, move to next line.

Input / Output Format

Input Format
An integer n (size of the square).
Output Format
Square pattern using *
Only border stars, inside is empty.
Constraints
• n ≥ 1

• Use loops only

Examples

Input:
5
Output:
***** * * * * * * *****

Example Solution (Public)

C++
void pattern_q9_hollow_square() {
    int n = 5;
    
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n; j++) {
            if(i == 1 || i == n || j == 1 || j == n) {
                cout << "* ";
            } else {
                cout << "  ";
            }
        }
        cout << endl;
    }
}

Official Solution Code

void pattern_q9_hollow_square() {
    int n = 5;
    
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n; j++) {
            if(i == 1 || i == n || j == 1 || j == n) {
                cout << "* ";
            } else {
                cout << "  ";
            }
        }
        cout << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.