Concept Explanation: Incrementing Integers/Counters

Printer-friendly version


Sometimes, you will want to be able to count how many times you have gone through a loop. Using a while loop and an integer variable, you can add this functionality. Without the ability to control the number of times a loop occurs, you would be forced to write out all of the commands each time you want to repeat. This leads to a needlessly long program and makes you a less effective programmer. The while loop is constructed like this:


The key variable in this is the "counter" integer. Each time we complete a loop we add one to the counter variable. Once the NXT has gone through this loop 3 times, the counter will equal 3 which is not less than our limit. This will cause the conditional statement to evaluate as FALSE and exit the loop. The double plus sign at the end of the variable name is shorthand for add 1 to this integer. It is the same as the following:

  • counter = counter + 1 ;