I have added numbers to make you understand how we will create this pattern using for loop
- As we know we first see how many lines of code needs to be printed, in this case it is 9 so i will iterate from 1 to n
- Since we will take user input it can be simply n which will be taken from user
- Here there is a difference that only stars are not being printed
- Along with the stars space is also being printed
- Inside outer i for loop there will be two loops one for star and another for space
- For space we will use variable s
- As we can see for i =1 there is no space,for i=2 there is 1 space and so on
- So we can say that s will iterate from 1 to i-1
- As for the pattern as we have seen before
- j will iterate from i to n
Code
#include<stdio.h>
#include<conio.h>
void main(){
int i,j,n,s;
clrscr();
printf("Enter number of lines ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(s=1;s<=i-1;s++)
{
printf(" ");
}
for(j=i;j<=n;j++)
{
printf("*");
}
printf("\n");
}
getch();
}
Note: scanf is used for taking user input
No comments:
Post a Comment