Control structures Chapter 3
Topics Assignment statement Selection: if..else Multi-way selection: switch Repetition Functions: setup(), draw(), mousePressed()
Repetition Three kinds of loops For loop While loop Do while loop
Loops syntax While loop int i =0; while (i < 100) { do something; i = i + 1; } For loop for (int i =0; i < 100; i = i +1) {
Loops syntax (contd.) int i = 0; do { do something; i = i + 1; } while (i < 100);
Lets apply this to drawing some shapes On to Processing: Draw 10 rectangles of different sizes and at different locations Draw 10 circles of different sizes and at different locations Parameter passing
Local Variables and Scope void setup() { int locVar1 = 301; println(“ lacvar1 in setup = “, locVar1); { int locVar2 = 290; println(“ locVar1 nested in setup = +“ locVar1); println(“locVar2 nexted in setup = +”locVar2); } println(“ local locVar2 out of scope = “+ locVar2); void func() println(“ local locVar1 out of scope = “+ locVar1); 2/19/2019
Boolean variable What are the different types of variable you have learned so far? int, float, char Here is one more: boolean A boolean varaible can take “true” or “false” as values. How to define it? How to initialize it? How to use it? boolean win; win = true; 2/19/2019
Variable naming conventions Variable name begin with lower case and the first word is all lowercase. If there are more than one word in the variable you begin the second with an upper case; do that same for more than two words of variable names too. Examples: setup draw drawAnimal drawAfricanAnimal drawSquaresCircles mySalary myDocs myNameAddressGrade 2/19/2019
Selection statement We already studied if..else See some examples in your text Lets look at out lab 1 and see how we use this if..else if (condition) { statements to be executed } else { statements to be executed} We could use nested if..else for multi-way selection.. 2/19/2019
Switch statement: multi-way selection Format or syntax: switch(val) { case 0: do this; break; case 1: do this; break; default: do this; } // lets use this in an example 2/19/2019
Example for switch int ct=0; int count = 0; int counta=0; int countb=0; int countc=0; void keyPressed() { switch (key) case 'a' : ct = counta++; break; case 'b' : ct = countb++; break; case 'c' : ct = countc++; break; default: ct = count++; } println(ct);