Learn creative coding writing simple programs

74. for() loops and other ways of typing less

Usually in programming languages there are many ways of doing a task. Some ways are shorter than others. In this episode we discover three things we can do to make our programs a little bit shorter. The first one is using increment "++", decrement "--", the add-assign "+=" and the subtract-assign "-=" instead of the longer version we have used in previous episodes: "i = i + 1", "i = i - 1", "i = i + 3" or "i = i - 3".
The second thing we discover is the "frameCount" variable. This is an integer variable that increases each time the draw() function is called. If you want to know how many animation frames Processing has drawn while running your program, have a look at the frameCount variable. Often in our past episodes we created such a variable that was increasing over time. Since we have one available, we don't need to create our own.
Finally we learn about the for() loop. Previously, if we wanted to run part of our code several times, we created a while() loop. It usually meant declaring and initializing a variable before calling while(), then writing a while() expression with a condition inside, and then inside the while() loop we increased a variable. We can do those three things at once in a for() loop, so we write one line instead of three. This way we also avoid forgetting the increasing of the tested variable, so using a for() loop is good for avoiding creating infinite loops.

Tags: for, loop, increment, decrement, framecount

Code editor

You can make changes to the code below. Then

Questions and comments

Try to stay close to the topic of this episode. Use the Processing forums for help with unrelated Processing projects (or hire me for help ;-)

To indicate that a word in your comment is code, use the `backtick`. Example
Do `float` and `int` smell similar?
To highlight code blocks, surround it with ``` code-fences ``` like this:
``` void setup() { size(600, 600); } ```