Printing star greater symbol in Java I need to print this in Java, but I feel that my code is too big:


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



public static void main(String[] args) {

    for(int i=0; i&lt;=3; i++) {
        for(int j=0; j&lt;=i; j++) {
            System.out.print("*");
        }
        System.out.println();
    }

    for(int j=1; j&lt;=3; j++) {
        for(int i=3; i&gt;=j; i--) {
            System.out.print("*");
        }
        System.out.println();
    }
}
Here is a lovely way to do it using only one nested for-loop:
for (int i = 0; i &lt; 7; i++) {
    for (int numStars = 0; numStars &lt; 4 - Math.abs(3 - i); numStars++) {
        System.out.print(&quot;*&quot;);
    }
    System.out.println();
}

This uses the Math.abs function to perform the calculation of how many stars to print.
If we take a look at a plot of the classic Math.abs we can see that it looks useful. We need to flip it upside-down though, this is done by taking 4 - abs(x) which would look like this. Finally, we need to switch it to the right a bit, so we modify the input to the function call and end up with this: 4 - abs(3 - x)
Images courtesy of wolframalpha.com
4-abs(x)

4-abs(3 - x)

Finally, here is a very flexible solution, which also works with even numbers:
int rows = 20;
double maximumValue = Math.ceil(rows / 2.0);
double shifted = maximumValue - 1;
for (int i = 0; i &lt; rows; i++) {
    int count = (int) (maximumValue - Math.abs(shifted - i));
    if (i &gt;= rows / 2 &amp;&amp; rows % 2 == 0) // slight fix for even number of rows
        count++;
    
    for (int numStars = 0; numStars &lt; count; numStars++) {
        System.out.print(&quot;*&quot;);
    }
    System.out.println();
}

This will output:
*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*