Skip to content

Instantly share code, notes, and snippets.

@robherley
Last active November 14, 2019 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robherley/925ccc95141a82a3d313959892af2497 to your computer and use it in GitHub Desktop.
Save robherley/925ccc95141a82a3d313959892af2497 to your computer and use it in GitHub Desktop.
Java program to print an ASCII '*' diamond
public class DiamondThing {
static int MAX_ROW_LEN = 5; // should always be an odd num to work properly
public static void main(String[] args) {
// from i -> the max, add 2 everytime
for (int currRowLen = 1; currRowLen <= MAX_ROW_LEN; currRowLen += 2) {
// we need to do a little arithmetic to figure out how many spaces
int numPrefixSpaces = MAX_ROW_LEN - currRowLen / 2;
for (int space = 0; space < numPrefixSpaces; space++) {
System.out.print(" ");
}
// print out the number of stars for our current row length
for (int star = 0; star < currRowLen; star++) {
System.out.print("*");
}
// print a newline after each row
System.out.print("\n");
}
// from the max -> zero, subtract 2 everytime
for (int currRowLen = MAX_ROW_LEN; currRowLen > 0; currRowLen -= 2) {
// same as above for spaces
int numPrefixSpaces = MAX_ROW_LEN - currRowLen / 2;
for (int space = 0; space < numPrefixSpaces; space++) {
System.out.print(" ");
}
// same as above for stars
for (int star = 0; star < currRowLen; star++) {
System.out.print("*");
}
// print a newline after each row
System.out.print("\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment