Iterate through 2 × n − 1 rows to form the upper and lower parts of the pattern, and compute a variable (comp) to control the spacing for each row.
Print leading spaces using an inner loop so that the stars shift toward the center and form the desired shape.
Use another inner loop to print stars at the first and last positions of the row and spaces in between, creating a hollow pattern.
C++
#include<iostream>usingnamespacestd;intmain(){intn=3;// Outer loop for rowsfor(inti=0;i<2*n-1;i++){intcomp;if(i<n)comp=2*(n-i)-1;elsecomp=2*(i-n+1)+1;// Print leading spacesfor(intj=0;j<comp;j++)cout<<" ";// Print stars and inner spacesfor(intk=0;k<2*n-comp;k++){if(k==0||k==2*n-comp-1)cout<<"* ";elsecout<<" ";}cout<<endl;}return0;}
Java
publicclassGfg{publicstaticvoidmain(String[]args){intn=3;// Outer loop for rowsfor(inti=0;i<2*n-1;i++){intcomp;if(i<n)comp=2*(n-i)-1;elsecomp=2*(i-n+1)+1;// Print leading spacesfor(intj=0;j<comp;j++)System.out.print(" ");// Print stars and inner spacesfor(intk=0;k<2*n-comp;k++){if(k==0||k==2*n-comp-1)System.out.print("* ");elseSystem.out.print(" ");}System.out.println();}}}
Python
defmain():n=3# Outer loop for rowsforiinrange(2*n-1):comp=2*(n-i)-1ifi<nelse2*(i-n+1)+1# Print leading spacesforjinrange(comp):print(' ',end='')# Print stars and inner spacesforkinrange(2*n-comp):ifk==0ork==2*n-comp-1:print('* ',end='')else:print(' ',end='')print()if__name__=="__main__":main()
C#
usingSystem;publicclassGfG{publicstaticvoidMain(){intn=3;// Outer loop for rowsfor(inti=0;i<2*n-1;i++){intcomp=i<n?2*(n-i)-1:2*(i-n+1)+1;// Print leading spacesfor(intj=0;j<comp;j++)Console.Write(" ");// Print stars and inner spacesfor(intk=0;k<2*n-comp;k++){if(k==0||k==2*n-comp-1)Console.Write("* ");elseConsole.Write(" ");}Console.WriteLine();}}}
JavaScript
functionprintPattern(n){// Outer loop for rowsfor(leti=0;i<2*n-1;i++){letcomp=i<n?2*(n-i)-1:2*(i-n+1)+1;// Print leading spacesletspaces=' '.repeat(comp);letstars;if(2*n-comp===1){stars='*';// single star case}else{stars='*'+' '.repeat((2*n-comp-2)*2)+'*';}console.log(spaces+stars);}}// Function callprintPattern(3);