Printing square pattern outline using For Loop in C++
This is a C++ program that uses loops to print a square pattern of stars. The pattern is printed in a single loop. Here is an explanation of how the program works:
- The program first declares three integer variables - i, j, and n.
- The user is prompted to enter a value for n.
- The program enters a loop that iterates n times. This loop is responsible for printing the rows of the square.
- Within the loop, there is another loop that iterates n times. This loop is responsible for printing the columns of the square.
- For each element in the square, the program checks whether it is on the border or not. If the element is on the border (i.e., if i is equal to 1 or n, or if j is equal to 1 or n), then a star is printed. Otherwise, a space is printed.
- The program then exits the loop and the main() function, returning 0.
- The square pattern is printed to the console.
Source Code
#include<iostream>
using namespace std;
int main()
{
int i,j,n;
cout<<"\nEnter the value:";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"\n";
for(j=1;j<=n;j++)
{
if(i==1||i==n||j==1||j==n)
cout<<" *";
else
cout<<" ";
}
}
return 0;
}
To download raw file
Click Here
Output
Enter the value:10
* * * * * * * * * *
* *
* *
* *
* *
* *
* *
* *
* *
* * * * * * * * * *