My for-loop that outputs a chessboard only works with even numbers, WHY?
Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a "#" character. The characters should form a chessboard.
/* Passing this string to console.log should show something like this: # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # When you have a program that generates this pattern, define a binding size = 8 and change the program so that it works for any size, */
outputting a grid of the given width and height.
Here's my answer:
let countPosition = 0, countLine = 0, size = 8, output = '';
for (let i =0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (countLine % 2 == 0) {
if (countPosition % 2 == 0) {
output += " ";
}
else {
output += "#";
}
} else {
if (countPosition % 2 == 0) {
output += "#";
}
else {
output += ' ';
}
} countPosition += 1;
} countLine += 1;
output += '\n';
}
console.log(output);
console.log(countLine);
My problem is that my code only works with even numbers!!!!! WHY???!! I have been stuck with this for a while I don't understand what's wrong with the code. It looks so logical why would it not work with odd numbers why? Any intellectual out there please explain this weird quirk.
This is a problem from Eloquent JavaScript: (https://eloquentjavascript.net/02_program_structure.html#i_swb9JBtSQQ)
(Edit: sorry for the weird formatting above, I couldn't get the chessboard to look okay without writing it as if it were a code snippet)
do you know?
how many words do you know