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
Below you can ask and answer questions related to this video. If your question is unrelated to the video, please post it at the Processing Forum as I'm unable to help with all of your programs and still have enough free time to eat and sleep :)
comments powered by Disqus