The book uses this code to draw a checkerboard. The only problem I’m having is understanding the sequence of how the individual squares on drawn on the checkerboard. When I do my calculations it only fills the checkerboard with squares in a diagonal direction from top left to bottom right. The book says the code does this loop 64 times for every square but I’m not sure how it does this 64 times.
For example lets say getHeight() = 72
sqSize = 9
moving in the inner most loop
double x = 0 * 9 ===> 0
double y = 0 * 9 ===> 0
GRect (0, 0, 9, 9,);
double x = 1 * 9 ===> 9
double y = 1 * 9 ===> 9
GRect (9, 9, 9, 9,);
double x = 2 * 9 ===> 18
double y = 2 * 9 ===>18
GRect (18, 18, 9, 9);
etc…
import acm.program.*;
import acm.graphics.*;
public class Checkerboard extends GraphicsProgram {
public void run(){
double sqSize = (double) getHeight() / N_ROWS;
for ( int i = 0; i < N_ROWS; i++ ){
for( int j = 0; j < N_COLUMNS; j++) {
double x = j * sqSize;
double y = i * sqSize;
GRect sq = new GRect(x, y, sqSize, sqSize);
sq.setFilled(( i + J ) % 2 !=0);
}
}
}
private static final int N_ROWS = 8;
private static final int N_COLUMNS = 8;
}
You have two loops – the second loop cycles through each value 0-7, and does so a total of 8 times, because that’s how many times the first loop runs. It appears in your explaination that you are incrementing both values at the same time, as if there was only one loop that increments both values each time through.
It may be helpful to print the values of i and j inside your loop.