Write a C++ program to print the hollow square star pattern using for loop.
#include<iostream> using namespace std; int main() { int i, j, side; cout << "Enter Side of a Hollow Square = "; cin >> side; cout << "Hollow Square Star Pattern\n"; for(i = 0; i < side; i++) { for(j = 0; j < side; j++) { if (i == 0 || i == side - 1 || j == 0 || j == side - 1) { cout << "*" << " "; } else { cout << " "; } } cout << "\n"; } return 0; }
This C++ example prints the hollow square pattern of a given character using a while loop.
#include<iostream> using namespace std; int main() { int i, j, side; char ch; cout << "Enter Side of a Hollow Square = "; cin >> side; cout << "Enter Symbol to Print in Hollow Square = "; cin >> ch; cout << "Hollow Square Pattern\n"; i = 0; while( i < side) { j = 0; while( j < side) { if (i == 0 || i == side - 1 || j == 0 || j == side - 1) { cout << ch << " "; } else { cout << " "; } j++; } cout << "\n"; i++; } return 0; }
Enter Side of a Hollow Square = 17
Enter Symbol to Print in Hollow Square = @
Hollow Square Pattern
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
SureshMac:C++Examples suresh$ cd "/Users/suresh/Desktop/C++Examples/" && g++ HollowSquareStar2.cpp -o HollowSquareStar2 && "/Users/suresh/Desktop/C++Examples/"HollowSquareStar2
Enter Side of a Hollow Square = 17
Enter Symbol to Print in Hollow Square = @
Hollow Square Pattern
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @