Steps
- First we will count the number of lines i.e 9
- So i will iterate from 1 to n // n is the value given by user for number of lines
- Now for inner loop j we need to see how many times the pattern is printed i.e 9
- It is same as n
- So j will iterate from 1 to n as well
- Now we need to see where stars are printed and where space is printed
- First we can see for the first line (horizontal) and last line (horizontal)
- These two conditions will be i==1 for first line and i==n for last line
- Next we see that each time first star is printed and last star is printed (vertical)
- These two conditions will be j==1 for first vertical line and j==n for last line
- These four conditions can be used together using logical or
- It will be used in a if condition inside j loop
- True part will print *
- False part will print space
- Remember to add "\n"
Code
#include<stdio.h>
#include<conio.h>
void main(){
int i,j,n;
clrscr();
printf("Enter number of lines ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==1 || i ==n || j==1 || j==n)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
getch();
}
Note: scanf is used for taking user input
No comments:
Post a Comment