For loops do the exact same thing as while loops except they are formatted differently. Just like while loops, we use for loops to make the boring, repetitive tasks of programming a lot easier. Some programmers like for loops better than while loops because they are more readable, while other programmers like while loops better because they are easier to understand.

We are using the variable “count” to count the number of times we will repeat the block of code. There are three parts to the for loop, the first part,
Lets say we want to sum all the integers from 1 to 10 (e.g. 1 + 2 + 3 +… + 9 + 10). An easy way to do this would be to use a for loop.
int sum = 0; for (int count = 1; count <= 10; count++) { sum += count; } println(“The sum of all integers from 1 to 10 is: “ + sum);
Lets examine what is happening in this loop. We start at 1 (count = 1), and end at 11 (count <= 10). First, Processing checks to see if 1 is less than or equal to 11. Since it is, Processing executes the code in the loop body. In the loop body we do a simple math operation, which is adding the current count to the sum. When the loop is finished, which means that it reaches the closing curly bracket ( } ), the count is incremented by 1. Processing then checks to see if the count is less than or equal to 10, if so, it executes the code in the loop body. It will keep looping until the count is greater than 10.
When the loop is finished, Processing will print:
Leave a Reply