I have a code from a book with a counter in it. I don't understand why it works the way it does. To be specific, how does it happen that counter counts the lines generated by "for" loop? I see that there is an "if" loop with relational operator and conditional expression but it's still isn't clear to me how the code "knows" to count the lines. Here is a code :
*/ class GalToLitTable { public static void main(String args[]) { double gallons, liters; int counter; counter = 0; for(gallons = 1; gallons <= 100; gallons++) { liters = gallons * 3.7854; // convert to liters System.out.println(gallons + " gallons is " + liters + " liters."); counter++; // every 10th line, print a blank line if(counter == 10) { System.out.println(); counter = 0; // reset the line counter } } } Any help would be much appreciated
12 Answers
There are three things going on here:
- You have a
forloop that is going to execute 100 times (from 1-100) - Within the loop, you'll increment your counter via the increment operator
++, which is essentially the same as callingcounter = counter + 1;. - Within your loop (after the increment), you'll check the current value to see if you should perform some action (in this case, resetting the counter).
You can see some annotated code below, which explains this a bit better, but I'd highly encourage you to see the links provided above for a bit more detail on the for loop and increment operator:
// Your counter int counter = 0; // The contents of this will execute 100 times for(gallons = 1; gallons <= 100; gallons++) { // Omitted for brevity // This increases your counter by 1 counter++; // Since your counter is declared outside of the loop, it is accessible here // so check its value if(counter == 10) { // If it is 10, then reset it System.out.println(); counter = 0; } // At this point, the loop is over, so go to the next iteration } counter ++; means counter = counter + 1; This line of code increments the counter by one on every iteration of the foor loop. The If-Clause, resets the counter to zero, when it has reached 10, as you see in counter = 0;. So after 10 iterations the counter reaches 10 and the condition of the if clause is true.