Kaue Pacheco
Kaue Pacheco

Reputation: 43

Can someone explain for me this remainder?

I am trying really hard to understand if ((x + y) % 2 == 0)... I can't understand the logic behind it.

var drawTable = "";
var size = 8;

for (x = 1; x <= size; x++) {
    for (y = 1; y <= size; y++) {
        if ((x + y) % 2 == 0) {
            drawTable += " ";
        } else {
            drawTable += "#";
        }
    }
    drawTable += "\n"
}

console.log(drawTable);

Thanks,

Kaue Pacheco

Upvotes: 2

Views: 63

Answers (5)

msagala25
msagala25

Reputation: 1806

if ((x + y) % 2 == 0) if you want a further explanation of this.

the modulo '%' is use to get the remainder of the division.

if you have for example:

5 % 2 = ?

In this scenario, It will divide 5 by 2. now the answer would be its remainder and not the quotient.

so the answer would be:

5 % 2 = 1

you will know if it is an even or odd number because you divided 5 by 2, and the remainder will distinguish whether it is an even or odd number by comparing it to 0. Obviously, all that equals to 0 are Even Numbers.

Upvotes: 0

dudeman
dudeman

Reputation: 1136

As all of the other answers have stated, if x+y is even, it will print out a space, and if it is odd, it will print out a '#'. The point of that appears to be to create a checkerboard pattern. Since you will start off with x = 1 and y = 1, the first line will be started with a space (since x+y is even), followed by a '#', followed by a space... until y is 9. Then the inner for loop will be exited and a new line started. On this new line x will start out at 2 and y at 1, so a '#' will be printed (since x+y is odd) followed by a space followed by... until y is 8 again. Then a new line will be started and that will continue until x is 9. At that point a checkerboard will be printed out.

Upvotes: 0

nag
nag

Reputation: 19

((x + y) % 2 == 0) is true only when x+y is even, otherwise it is false. If is true it will add a space otherwise it will add # symbol.

Upvotes: 1

Ann Nacional
Ann Nacional

Reputation: 75

It goes to show if the sum of x and y is an even number. If x=1 and y=3, then x+y will be 4 and 4 will be divided. If it has a 0 remainder (like the number 4 does), it is an even number. Else, it is an odd number.

Your code will only execute the content inside the if condition of ((x+y)%2==0) if your remainder is zero. Hope this helps ^_^

Upvotes: 1

John3136
John3136

Reputation: 29266

if ((x + y) % 2 == 0) is the same as if (x + y) is an even number.

Upvotes: 1

Related Questions