90 likes | 245 Views
ICS 3U. The Counted Loop FOR LOOPS. For Loops - Introduction. Loops are used to repeat a block of statements. A For Loop is used to execute the statements inside a fixed number of times. A For Loop in ActionScript looks like: for (initialization; condition; increment) {
E N D
ICS 3U The Counted Loop FOR LOOPS
For Loops - Introduction Loops are used to repeat a block of statements. A For Loop is used to execute the statements inside a fixed number of times. A For Loop in ActionScript looks like: for (initialization; condition; increment) { Statement(s) to be repeated } Initialization performed only the first time the loop is executed, sets the starting value of the variable that is used to control the loop Condition a Boolean expression that is evaluated before each execution of the loop, tells when to stop the loop Increment performed after each execution of the loop, it advances the value of the loop control variable
For Loops - Example A Simple Count to 10 vari: int; for (i =0; i <= 10; i++) adds one { trace(i); }
For Loops – Example Counting Backwards 10 to 1 vari: int; for (i = 10; i >=0; i--) subtracts one { trace(i); }
For Loops - Example Generating 25 random numbers between 1 and 100 varrandnum: int; vari: int; varhigh:int = 100; var low: int = 1; for (i = 0; i <= 25; i++) { randnum = Math.floor(Math.random ...); trace (randnum); }
For Loops - Example Write a For Loop that will: Output all numbers between 1 and 100 that are divisible by 3.
Additional Notes • Can I only increment my loop control variable by 1? Can I go up by 5’s? 2’s? • A single letter variable?! • we typically use these as loop control variables in the for loops (counted loops). • It is ok in these instances • Accumulators • Many times in loops we want to accumulate a value. Keep a running total, keeping a score, counting the number of even numbers, etc.
Accumulators Write a for loop that will total 5 random numbers generated. Can also use subtract: newvalue= newvalue – randnum; OR newvalue -= randnum;
Exercises See Website for the exercises ... NOW – Get to WORK!!