Explain creating a pyramid in Java

后端 未结 7 1277
独厮守ぢ
独厮守ぢ 2020-12-18 17:04

I am in a beginner java programming class and currently reviewing loops. If there is one thing I just do not understand, it\'s pyramids. I have researched the book exercis

7条回答
  •  囚心锁ツ
    2020-12-18 17:47

    We can make pyramid with one for loop as well, making it performance efficient code in terms of execution time.

    Here is the code which prints pyramid of asterisk.

    public class PyramidPrinting {
    
        public static void main(String[] args) {
            int h = 5;
            int i,j;
            char[] arr = new char[2*h-1];
    
            for(i=h-1,j=h-1; i>=0 && j<=2*h-1; i--,j++){
                arr[i]='*';
                arr[j]='*';
                System.out.println(arr);
            }
        }
    }
    

    output:

        *
       ***
      *****
     *******
    *********
    

提交回复
热议问题