Sunday, October 1, 2023

7.Easy triangle pyramid

 



I have added numbers to make you understand how we will create this pattern using for loop
Also refer 4.Triangle pattern with left spacing because it is derived from it
  • As we know we first see how many lines of code needs to be printed, in this case it is 9 
  • Since we will take user input it can be simply n which will be taken from user
  • 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
  • For i=1 ,the number of space is 8,for i=4 it is 5
  • Here we can see space is being printed n-i times
  • So s will iterate from from 1 to n-i
  • The stars that are printed are same as i
  • If we observe carefully we can see that there is a space after every star that is printed
  • So the j loop will iterate from 1 to i but now it will print
  • "* " i.e star along with space each time
  • Remember to print "\n" to make it move to next line

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<=n-i;s++)
                {
                   printf(" ");
                  }
          for(j=1;j<=i;j++)
               {
                 printf("* ");   
                   }
           printf("\n");
     }

getch();
}
Note: scanf is used for taking user input,s is for space , j for pattern


No comments:

Post a Comment