Regarding a star pattern

前端 未结 3 1653
独厮守ぢ
独厮守ぢ 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:15

    The pattern consist of N * 2 - 1rows. For each row columns are in increasing order till Nth row. After Nth row columns are printed in descending order.

    Step by step descriptive logic to print half diamond star pattern.

    1. Input number of columns to print from user. Store it in a variable say N.
    2. Declare a variable as loop counter for each column, say columns = 1.
    3. To iterate through rows, run an outer loop from 1 to N * 2 - 1. The loop structure should look like for(i=1; i<N*2; i++).
    4. To iterate through columns, run an inner loop from 1 to columns. The loop structure should look like for(j=1; j<=columns; j++). Inside this loop print star.
    5. After printing all columns of a row, move to next line.
    6. After inner loop check if(i <= N) then increment columns otherwise decrement by 1.

      int columns=1;
      int N=3;
      
      for(int i=1;i<N*2;i++)
      {
          for(int j=1; j<=columns; j++)
          {
              System.out.print("*");
          }
      
          if(i < N)
          {
              /* Increment number of columns per row for upper part */
              columns++;
          }
          else
          {
              /* Decrement number of columns per row for lower part */
              columns--;
          }
      
          /* Move to next line */
          System.out.print("\n");
      }
      
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2021-01-29 15:39

    You just have to write in reverse the loop, to start from the upperBound - 1. See the code bellow:

    int numberOfLines = 3;
    for (int i = 1; i <= numberOfLines; i++) {
        for (int j = 1; j < 2*i; j++){
            System.out.print("*");
        }
        System.out.println();
    }
    for (int i = numberOfLines - 1; i > 0; i--) {
        for (int j = 1; j < 2*i; j++){
            System.out.print("*");
        }
        System.out.println();
    }
    
    0 讨论(0)
提交回复
热议问题