/home/wpollock1/public_html/restricted/Java1/Diamond.java
// Classic Java assignment (after learning for-loops): Draw a filled diamond
// pattern on the console. This is a model solution for a 15x15 diamond, but
// any odd number will work. The shape is drawn with stars ("*") and spaces.
// Note the solution shown here doesn't work for diamonds with an even number.
// In this solution, a single outer for-loop was used to draw all rows. Each
// of the first half of the rows grows by two stars per row, and shrinks by
// two stars per row in the second half of the diamond. Perhaps using two
// for-loops, one for each half, would be clearer.
//
// Written 9/2018 by Wayne Pollock, Tampa Florida USA
public class Diamond {
public static void main ( String [] args ) {
final int GRID_SIZE = 15; // 15 rows by 15 columns
final int INDENT = 10; // Extra space on the left to indent the diamond.
int diamondRowWidth = 1; // Initial width of the first row (always 1).
int diamondRowWidthChange = 2; // add 2 (or -2) to the width for each row
System.out.println(); // Add a blank row.
// For each row of the diamond:
for ( int row = 0; row < GRID_SIZE; ++row ) {
// Calculate the number of leading spaces required for this row:
int leadingSpaceWidth = INDENT + (GRID_SIZE - diamondRowWidth) / 2;
// Print the leading spaces:
for ( int i = 0; i < leadingSpaceWidth; ++i )
System.out.print( " " );
// Print one row of the diamond:
for ( int i = 0; i < diamondRowWidth; ++i )
System.out.print( "*" );
System.out.println(); // End the row with a newline
// In the bottom-half, the diamond shrinks instead of growing:
if ( diamondRowWidth >= GRID_SIZE )
diamondRowWidthChange = -2;
// Adjust diamond width of next row:
diamondRowWidth += diamondRowWidthChange;
}
}
}