Sunday, October 1, 2023

10.Inverted Pyramid

 

  • As always we  count the number of times the pattern is printed so it is 9
  • In this case we will iterate from n-1 to 0 i.e n times
  • It is done because it will be easy to use the logic used in 9.Pyramid
  • For space,first for n-1 there is no space 
  • For n-2 i.e 7 there is one space and so on
  • So for s we can iterate from i to n-2 
  • So for i=8 n-2 is 7 so condition(8≤7) is false and no space is printed
  • For i=7 n-2 is 7 so condition (7≤7) is true so one space is printed
  • It will be like this for(s=i;s<=n-2;s++) //You can also use s<n-1 that is same
  • Now for the main pattern for i=8, stars printed are 17
  • For i=1, stars printed are 3
  • For i=0 it is only 1
  • We can find a pattern that the number of times they are printed is (2*i)+1 times
  •  So j will iterate from 1 to (2*i)+1
Code

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,s,n;
clrscr();
printf("Enter number of lines ");
scanf("%d",&n);
for(i=n-1;i>=0;i--)
      {
            for(s=i;s<=n-2;s++)
            {
                printf(" ");  
             }
             for(j=1;j<=(2*i)+1;j++)
               {
                  printf("*");
                }
               printf("\n");
       }
getch();
}

Note:scanf is used for taking user input

No comments:

Post a Comment