From cc23f7c914639bd1aba7f030cfd41f4d66a0493d Mon Sep 17 00:00:00 2001 From: gauthiier Date: Sun, 15 Jan 2023 12:17:36 +0100 Subject: [PATCH] loop --- 2.Ghost-Writing.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/2.Ghost-Writing.md b/2.Ghost-Writing.md index b2c720b..c7da1b9 100644 --- a/2.Ghost-Writing.md +++ b/2.Ghost-Writing.md @@ -54,3 +54,46 @@ function keyTyped() {

+## Sketch: 2.1 Array + Index + Loop + +```javascript +// Array + Index + Loop! + +var NAMES = ["David", "Karin", "Sigrid", "Nanna", "Laura", "Maaike"]; +var ACTIVITIES = ["piano", "tennis", "chess", "records"]; +var INDEX = 0; + +function setup() { + createCanvas(400, 400); +} + +function draw() { + background(220); +} + +function keyTyped() { + if(key == 'x') { + for(let i = 0; i < 4; i++) { + print(NAMES[INDEX] + " likes to play " + ACTIVITIES[i]); + } + } +} + +// Reference: https://p5js.org/reference/ +``` + +### 🤔 How do for-loops work? + +```javascript +for(let i = 0; i < X; i++) { + // do_somethings(); +} +``` +where the 3 statements +``` +-> "let i = 0" is the declaration and initialisation of the control variable (i) +-> "i < X" is the continuation condition (i.e. if the condition is true, then executed the statement in the loop > do_something();, exit the loop when it is false) +-> "i++" is the incremental/update statement that is executed at the end of the loop (i.e. after the statement in the loop as been executed) +``` + +