I am trying to print below star pattern
*
***
*****
***
*
I am using below logic to print :
*
***
*****
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.
N.columns = 1.1 to N * 2 - 1. The loop structure should look like for(i=1; i<N*2; i++).for(j=1; j<=columns; j++). Inside this loop print star.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");
}
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();
}
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();
}