CS4ALL Computer Science For All Of Us
  • Home
  • Community
  • Workshop
    • Workshop Info
    • Schedule
    • Location
    • Sponsors
  • Resources
    • Scratch Resources
CS4ALL
  • Home
  • Community
  • Workshop
    • Workshop Info
    • Schedule
    • Location
    • Sponsors
  • Resources
    • Scratch Resources
  • Home
  • Processing
  • Beginner
  • For Loops

For Loops

July 11, 2016 Leave a Comment Written by Keith Atkinson

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,

int count = 0
, tells the computer to start with the value 0 for count. The second part of the loop,
count < 4
, tells Processing to keeping running the loop while the count is less than 4. The third part of the loop,
count++
, tells Processing to increment the count variable by 1 every time the loop finishes.So, in the example above, if we start at 0 and end at 4 we will loop a total of 4 times (count = 0, count = 1, count = 2, count = 3) .

Example

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:

The sum of all integers from 1 to 10 is: 55
Beginner, Processing
While Loops
Functions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Comments

    Categories

    • Processing
      • Beginner
    • Scratch
      • Beginner