Print Pyramid Star Pattern
PRINTING PATTERN:
*
***
*****
*******
PREREQUISITE:
Basic knowledge of C language and use of loops.
ALGORITHM:
- Take the number of rows as input from the user and store it in any variable.(‘r‘ in this case).
- Run a loop ‘r’ number of times to iterate through each of the rows. From i=0 to i<r. The loop should be structured as for( i=0 ; i<r : i++).
- Run a nested loop inside the main loop to print the spaces before the pyramid. From k=r to k>i +1. The loop should be structured as for( k=r; k>i+1 ;k–).
- Inside this nested loop print white space.
- Run another nested loop inside the main loop after the previous loop to print the stars in each column of a row. From j=0 to j<=i*2. The loop should be structured as for( j=0 ; j<i*2; j++).
- Inside this nested loop print star.
- Move to the next line by printing a new line . printf(“/n”).
Code in C:
#include<stdio.h> int main() { int i,j,k,r; //declaring integer variables i,j,k for loops and r for number of rows printf("Enter the number of rows :\n"); //Asking user for input scanf("%d",&r); //saving number of rows in variable r for(i=0;i<r;i++) //outer loop for number of rows { for(k=r;k>i+1;k--) //nested loop for number of spaces { printf(" "); //printing spaces } for(j=0;j<=i*2;j++) //nested loop for printing stars { printf("*"); //printing stars } printf("\n"); //printing newline } }
TAKING INPUT:
DISPLAYING OUTPUT:
Login/Signup to comment
n=4
c=1
for i in reversed(range(0,n)):
print(” “*i+”*”*c)
c=c+2
int i,j,k;
for(i=1;i<=4;i++)
{
for(k=1;k<=4-i;k++){
System.out.print(" ");
}
for(j=1;j<=i*2-1;j++){
System.out.print("*");
}
System.out.println();
}
#include
int main()
{
int row, col, k, j;
for (row = 0; row row; k–)
{
printf(” “);
}
for (col = 0; col <= row; col++)
{
printf("* ");
}
for (j = 2; j <= row + 1; j++)
{
printf("* ");
}
printf("\n");
}
}
n = int(input())
c = 1
for i in range(1,2*n,2):
print(” “*(n-c)+”*”*i+” “*(n-c))
c +=1
#include
int main()
{
int i,j,n,p;
printf(“enter rows”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=i;j<=n-1;j++)
{
printf(" ");
}
p=0;
while(p<(2*i-1))
{
printf("*");
p++;
}
printf("\n");
}
}
#include
int main(){
int i,row=4,sp,p;
for (i = 0; i i; sp–)
{
printf(” “);
}
for (p = 1; p <= 2*i+1; p++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Python code
n = int(intput())
k = 2*n – 1
for i in range(1,n+1):
print(‘ ‘*(k//2),end=””)
print(‘*’*(2*i – 1))
k = 2*(n-i)-1
#include
int main()
{
int i,j,k,n;
scanf(“%d”,&n);
for(i=0;i<n;i++){
for(k=0;k<n-i-1;k++){
printf(" ");
}
for(j=0;j<=i*2;j++){
printf("*");
}
printf("\n");
}
return 0;
}
for i in range(n):
print(‘ ‘*(n-1-i)+’*’*(2*i+1))
/* a=number of rows*/
for(i=0;ii;j–)
{
printf(” “);
}
for(k=1;k<=(2*i-1);k++)
{
printf("*");
}
}
python
———–
n=int(input())
for i in range(n):
for j in range(n-i):
print(” “,end=””)
for j in range((2*i)+1):
print(“*”,end=””)
print(end=”\n”)