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.
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();
}
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();
}
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.
- Input number of columns to print from user. Store it in a variable say
N
. - Declare a variable as loop counter for each column, say
columns = 1
. - To iterate through rows, run an outer loop from
1 to N * 2 - 1
. The loop structure should look likefor(i=1; i<N*2; i++)
. - 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. - After printing all columns of a row, move to next line.
After inner loop check
if(i <= N)
then incrementcolumns
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