Översikt

  • Flow control, part 2

    Today we'll learn how to repeat things with for loops and also experiment a little with while loops, which in this family of languages – but not some others – are easily interchangeable.

    As we know by now, we can nest flow control statements ie. inside a for can be another for or if or many when needed. Nested loop example: nestedloops.pde

    At times it can be confusing that we can (slowly) repeat things by simply placing them inside draw but also using actual loops. The difference is that when we do a loop with for/while things will be repeated for each frame separately.

    Grouping conditions

    Conditionals can be grouped, if you want to do more comparisons at once:

    • And: &&
    • Or: ||


    For example: if(mouseX>100 && mouseX<200)

    Indentation (sisennys)

    It’s a good common practice to indent the contents of compound statements a few characters to the right, so that they are visually aligned. This way you can instantly spot the statements that are on the same level. Processing will do most of it for you automatically, but if your code has gotten ugly, you can clean it up by selecting it and then clicking Edit – Auto Format.

    Homework

    Using nested for loops draw a grid of white squares as seen below. In addition, implement a "mouseover" where a square turns red if the mouse is over it. Use if and suitable conditions for that.

    Grid

    Example solution: grid.pde