120 likes | 288 Views
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 i nt i =0;
E N D
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 inti =0; while (i < 100) { do something; i = i + 1; } For loop for (inti =0; i < 100; i = i +1) { do something; }
Loops syntax (contd.) inti = 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); println(“ local locVar2 out of scope = “+ locVar2); }
Boolean variable What are the different types of variable you have learned so far? int, float, char Here is one more: boolean A booleanvaraible can take “true” or “false” as values. How to define it? How to initialize it? How to use it? boolean win; win = true;
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
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..
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
Example for switch intct=0; int count = 0; intcounta=0; intcountb=0; intcountc=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); }