Begginer asks for command 'for'

I am a beginner in the world of programming and so far I have only seen how to draw basic shapes and apply color to them. I am studying a programming subject at the university, in a university degree in design and this field is very tedious for me.

I need help with the for command. I have read chapter 4 of ‘Getting started with p5js’ but I still don’t understand how this command works.
For example:

what parameter of the command does each number refer to?
(extract from chapter 4 of ‘Getting started with p5js’

How could I draw 100 vertical lines that would occupy half the canvas of a canvas that measured 1000,500 with a for command? And with another for command, the rest of the canvas with 100 more vertical lines? Thats for my university homework

Sorry for such a long question


Let’s break the for statement with the following pseudo code :

for (start; condition; eachTime) {
  // block

The goal of a for loop is to execute some code repeatedly.

If you want to do a loop, you need to tell to the program when it’s going to end. That’s the role of the condition statement : if it’s true then continue the loop, stop otherwise.

So this is the flow of the program :

  • The start statement is executed when the loop starts

  • We execute all the code inside the block (delimited by the brackets { })

  • the eachTime statement is executed at the end of every loop.

So if we take the code from the image you sent :

for (var i = 20; i < 400; i += 8) {

This is what the computer do :

  1. Sees the for loop

  2. Execute : var i = 20 which is a variable declaration and initialization (20 is stored into i)

  3. Check if the condition is true : i < 400 which is resolved to 20 < 400 which is true
    → We can loop

  4. Execute the lines inside the block : console.log(i); which prints 20

  5. End of the loop : execute the i += 8 statement so now i is equal to 20 + 828

  6. Start the loop again, check the condition : i < 40028 < 400 which is true

  7. Print out 28

  8. and continue until…

  9. i is now 396 and we add 8 to it so → i = 396 + 8 = 404

  10. Check the condition 404 < 400 which is false! → The loop stops


Half of the canvas is 1000 / 2

for 100 lines you need to step (1000/2) / 100 between the lines

for (int i = 5; i < (1000/2); i+=(1000/2) / 100) {
    line( i, 10, i, height-10);

Actually, the lines on the left would look the same like on the right side with this data.

This for-loop is similar, just add 500


Thank you for explaining it to me in such detail! Its been super helpfull to understand. I had to read it a couple of times because I still think it’s difficult but ill manage it to understand

1 Like

thanks a lot @Chrisir
it works! you guys are the best