Java for loop print shape using nested for loop 5

Question

We would like to output the following shape using nested for loop.

pattern://from   w w  w.j  a va 2 s . co  m
       * 
      *** 
     ***** 
    ******* 
   ********* 
    ******* 
     ***** 
      *** 
       * 



public class Main {
    public static void main(String[] args){
        // 2nd half of each half
        int extra = 0;

        // top half
        for(int i=1; i<5; i++){
            // blank spaces
            for(int j=5 - i; j>0; j--){
                System.out.print(' ');
            }
            for(int k=0; k<i + extra; k++){
                System.out.print('*');
            }
            System.out.println();
            extra++;
        }

        // bottom half
        for(int i=5; i>=0; i--){
            // blank spaces
            for(int j=0; j<5 - i; j++){
                System.out.print(' ');
            }
            for(int k=0; k<i + extra; k++){
                System.out.print('*');
            }
            System.out.println();
            extra--;
        }
    }
}



PreviousNext

Related