Filled Triangle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class TriFilled{ public static void main(String args[]){ int height = 5; // loop for total height of triangle for(int i=1;i<=height;i++){ // loop for first half space for(int j=1;j<i;j++){ System.out.print(" "); } //loop for first half stars for(int k=i;k<height;k++){ System.out.print("*"); } //loop for second half of stars for(int l=i;l<=height;l++){ System.out.print("*"); } // break current row System.out.println(); } } } |
Hollow Triangle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
class TriHollow{ public static void main(String args[]){ int height = 5; // loop for total height of triangle for(int i=1;i<=height;i++){ // loop for first half space for(int j=1;j<i;j++){ System.out.print(" "); } //loop for first half stars for(int k=i;k<height;k++){ // put star only if k starts or height is 1 if(k==i || i==1){ System.out.print("*"); } else{ System.out.print(" "); } } //loop for second half of stars for(int l=i;l<=height;l++){ //put start only if l ends or height is 1 if(l==height || i==1){ System.out.print("*"); } else{ System.out.print(" "); } } // break current row System.out.println(); } } } |