HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Printing star greater symbol in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stargreatersymboljavaprinting

Problem

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=j; i--) {
            System.out.print("*");
        }
        System.out.println();
    }
}

Solution

Here is a lovely way to do it using only one nested for-loop:

for (int i = 0; i < 7; i++) {
    for (int numStars = 0; numStars < 4 - Math.abs(3 - i); numStars++) {
        System.out.print("*");
    }
    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 = rows / 2 && rows % 2 == 0) // slight fix for even number of rows
        count++;
    
    for (int numStars = 0; numStars < count; numStars++) {
        System.out.print("*");
    }
    System.out.println();
}


This will output:

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

Code Snippets

for (int i = 0; i < 7; i++) {
    for (int numStars = 0; numStars < 4 - Math.abs(3 - i); numStars++) {
        System.out.print("*");
    }
    System.out.println();
}
int rows = 20;
double maximumValue = Math.ceil(rows / 2.0);
double shifted = maximumValue - 1;
for (int i = 0; i < rows; i++) {
    int count = (int) (maximumValue - Math.abs(shifted - i));
    if (i >= rows / 2 && rows % 2 == 0) // slight fix for even number of rows
        count++;
    
    for (int numStars = 0; numStars < count; numStars++) {
        System.out.print("*");
    }
    System.out.println();
}
*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*

Context

StackExchange Code Review Q#40880, answer score: 30

Revisions (0)

No revisions yet.