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
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) {
console.log(i);
}
This is what the computer do :
Sees the for loop
Execute : var i = 20 which is a variable declaration and initialization (20 is stored into i)
Check if the condition is true : i < 400 which is resolved to 20 < 400 which is true
→ We can loop
Execute the lines inside the block : console.log(i); which prints 20
End of the loop : execute the i += 8 statement so now i is equal to 20 + 8 → 28
Start the loop again, check the condition : i < 400 → 28 < 400 which is true
Print out 28
and continue until…
i is now 396 and we add 8 to it so → i = 396 + 8 = 404
Check the condition 404 < 400 which is false! → The loop stops
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