Regarding a star pattern

落花浮王杯 提交于 2019-12-02 23:45:15

问题


I am trying to print below star pattern

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

I am using below logic to print :

*
***
*****

Code for first half:

int i, j;
for (i = 1; i <= 3; i++) {
    for (j = 1; j <= i; j++)
        System.out.print("*");
    for (j = i - 1; j >= 1; j--)
        System.out.print("*");
    System.out.println();
}

But still I am not sure about how to print the whole structure.


回答1:


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();
}



回答2:


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();
}



回答3:


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");
    }
    


来源:https://stackoverflow.com/questions/22681510/regarding-a-star-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!