# Thread: Little bit confused on the Mod Operator

1. ## Little bit confused on the Mod Operator

Here's a sample from my review:

7) How many times does the letter A print out in the following segment of code?
Code:
```int i=0;
while (i < 20) {
i++;
if (i%5 > 2) {
continue;
}
printf(“A”);
}```
A) 10 B) 12 C) 15 D) 20 E) NOTA

The answer is b, but I dont understand the if statement.
For instance, I do understand if something like 12%5, which is 2 because 5 can only go up to 10, so the remainder is 2.
But when it's something like 19%200, it throws me off

2. If the remainder of i / 5 is > 2 then don't print an "A"

3. 1234567890
YYNNYYYNNY = 6

Now multiply that by 2.

Quzah.

4. But when it's something like 19%200, it throws me off
19 / 200 is zero, remainder 19.

5. Or to be really picky, that segment of code wont compile (as posted) because it contains smart-quotes around the "A", rather than regular ones.

6. Originally Posted by Dino
19 / 200 is zero, remainder 19.
So if thats the case, then wouldnt the program read like this:

Code:
`if (i%5 > 2)`
1=5
2=5
3=5
4=5
5=0
6=1
7=2
8=3
9=4
10=0

so i= 1, 2, 3, 4, 8 and 9 is true since it is bigger than two

am I understanding this correctly?

7. No, look back at my earlier post:

1%5 = 1 > 2 = F
2%5 = 2 > 2 = F
3%5 = 3 > 2 = T
4%5 = 4 > 2 = T
5%5 = 0 > 2 = F

The % operator is basic division, before they taught you about decimals.

1 / 5 = 0 R 1
2 / 5 = 0 R 2
3 / 5 = 0 R 3
4 / 5 = 0 R 4
5 / 5 = 1 R 0

So you look at the remainder, and see if that is bigger than 2.

Quzah.

8. Originally Posted by Neotriz
So if thats the case, then wouldnt the program read like this:

Code:
`if (i%5 > 2)`
1=5
2=5
3=5
4=5
5=0
6=1
7=2
8=3
9=4
10=0

so i= 1, 2, 3, 4, 8 and 9 is true since it is bigger than two

am I understanding this correctly?
No that's not quite right. It should be:

0≡0
1≡1
2≡2
3≡3
4≡4
5≡0
6≡1
7≡2
8≡3
9≡4
10≡0

All of those are modulo five of course. Note how the right is never 5 or greater.

9. 1 % 5 = 1
2 % 5 = 2
3 % 5 = 3 First match
4 % 5 = 4. 2nd match
5 % 5 = 0
6 % 5 = 1
7 % 5 = 2
8 % 5 = 3 3rd match

and so on

and so on

10. Thank you! I was actually looking the other way around

Thanks alot, that clears up

Popular pages Recent additions