Help me understand for loops with if statements

+2 TENGEN TOPPA GURREN LAGANN · November 21, 2014

for (int cnt = 0; cnt < 200; cnt++) {
            if (cnt % 13 == 0) {
                System.out.println("#: " + cnt);

This program works just fine but i don't understand it.
How is variable cnt get a remainder by dividing it to 13 when cnt is initialized to zero

cnt % 13 == 0

cnt divided by 0 so there's no remainder.
so it prints out

#: 0

so it loops back again and it checks if variable cnt is still less than 200
cnt divided by 13 no remainder again so i'ts still zero but it it prints out 13

#: 13

so again loops back again then it prints out

#: 26

It keeps adding.
Does the number 13 assigns to variable cnt??
Could someone explain this better to me. thank you.

Post a Reply


Oldest  Newest  Rating
+3 Homer Simpson · November 22, 2014
% is the modulus operator which is just a fancy word people use to make themselves look smart. What it should really be called is remainder.
So what is happening here is cnt is looping through starting from 0 and increasing each time. 

When cnt has the value of 13. The if statement is true because 13 divided by 13 has a remainder of 0.
then it keeps looping each number is being tested but none meet the condition until 26. 
26 divided by 13 also has a remainder of 0 because 13 goes into 26 two times.
+1 TENGEN TOPPA GURREN LAGANN · November 22, 2014
Oh man!  thanks for the explanation i just understand it now!
0 Homer Simpson · November 22, 2014
No problem :D
-1 Developer John · November 22, 2014
Does the modulus do both dividing and finding the remainder?
0 Developer John · November 22, 2014
Idk, the modulus confused me, so I didn't really know how it functioned.
0 Homer Simpson · November 22, 2014
I don't really understand the question. Like Rick said it's probably dividing under the hood but all it does is return the remainder. 

One thing to note is that if the first number being divided is smaller then the divisor the. It returns the first number.

3 % 5 = ?

5 cannot go into 3 assuming they're integer values. So there would be a remainder of 3.
0 Developer John · November 22, 2014
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator