Reputation: 6616
I can not understand how this code draws a complete chess board not only 8 squares
Especially : How for-loop
it works.
import acm.program.*;
import acm.graphics.*;
public class chbord extends GraphicsProgram {
/* number of columns */
private static final int Ncolumns = 8;
/* number of rows*/
private static final int Nrows = 8;
public void run() {
int sqSize = getHeight() / Nrows;
for (int i = 0; i < Nrows; i++) {
for (int j = 0; j < Ncolumns; j++) {
int x = j * sqSize;
int y = i * sqSize;
GRect sq = new GRect(x, y, sqSize, sqSize);
sq.setFilled(((i + j) % 2) != 0);
add(sq);
}
}
}
}
Upvotes: 1
Views: 260
Reputation: 974
the outer and inner loop will create an NRows*NColumns grid and the modulus operator (%) will color every other square since there are only two values with MOD 2.
Upvotes: 0
Reputation: 49104
The first time the outer loop runs, the inner loop runs completely (8 times). Then the outer loop runs a second time and the inner loop is then run completely once again (another 8 times).
This continues through the eighth row.
So you get 8 rows drawn, but each row is drawn as 8 columns.
Result: all 64 squares are drawn.
Especially : How for-loop it works.
A For-loop is a key part of programming. Here are some explanation articles:
Upvotes: 1
Reputation: 28292
This is an example of a nested loop - one loop inside another. The outer loop causes the code it contains to be executed for values of i between 0 and nrows - 1, inclusive. The inner loop causes the code it contains to be executed for values of j between 0 and ncols - 1, inclusive. Since the code in the inner loop is executed for n values of i, and for each of these values of i, m values of j, the total number of executions is nm.
Upvotes: 0
Reputation: 4278
While both the posters above are correct consider that the second loop runs 8 times for each one time the first loop runs. To demonstrate put two different System.out.println statements in each loop and view the order that they are printed in.
Upvotes: 1
Reputation: 19295
It's because there are actually two for loops, not just one. This is called "nesting" loops, and it's the typical approach used to create row x column grids such as a chessboard.
Upvotes: 0
Reputation: 424983
There's a loop within a loop:
for (int i = 0; i < Nrows; i++) {
for (int j = 0; j < Ncolumns; j++)
Each loop has 8 iterations:
/* number of columns */
private static final int Ncolumns = 8;
/* number of rows*/
private static final int Nrows = 8;
That makes 64 total iterations (8 x 8) through the inner loop - one for each chess square.
Upvotes: 2