Regarding a star pattern

前端 未结 3 1737
独厮守ぢ
独厮守ぢ 2021-01-29 14:51

I am trying to print below star pattern

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

I am using below logic to print :

*
***
*****

3条回答
  •  情深已故
    2021-01-29 15:36

    It will perhaps make sense to go in as simple steps as possible.

    First, you need five lines, so

    for (i = 1; i <= 5; i++) {
    

    Next, on line i, determine the number of asterisks you are going to place. It is five asterisks on line 3, two less with each step above or below that line.

        int len = 5 - Math.abs (i - 3) * 2;
    

    Then, just place them in a single loop:

        for (j = 1; j <= len; j++)
            System.out.print("*");
    

    And include a newline:

        System.out.println();
    }
    

提交回复
热议问题