Last active
November 14, 2019 02:44
-
-
Save robherley/925ccc95141a82a3d313959892af2497 to your computer and use it in GitHub Desktop.
Java program to print an ASCII '*' diamond
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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