******************************************************************************* 0) Administrative - questions about A2? - hw: read 6.4-6.7 (next person) - exam back: avg 71, report format, go over written part, answer questions 1) Last time- finished if statements (conditionals) - finish up exercises - quiz for chapter 5 2) Go over 6.1-6.3 in your groups 3) Highlights of material A. Big picture: sometimes you want to repeat something a lot of times - creating 10 Robots, or 100 - impractical to type even one line 100 times - a loop lets you repeat a block of code a certain # of times, or until a certain condition is met B. Simplest version: while loop - add 3 robots to an arena int num = 0; while (num < 3) { Robot r = new Robot(...); arena.add(r); num++; } - you do not have to do this in A2, but you may if you want - boolean condition, loop header, loop body, rule with braces - exactly what code does; draw diagram for it - count-controlled: runs a fixed number of times (3) * Infinite loop- condition never goes false - if you forget to update the count variable (num) - book has other examples, and we'll debug some * Off-by-one- boundary conditions off - usually go from 0 to < n to run n times (or: 1 to <= n) C. Sentinel-controlled loop: runs til condition met, as long as necessary - get a non-negative input value with a while loop int x = getInt(); while (x < 0) { S.o.p("Try again"); x = getInt(); } - priming read (x declared and initialized outside loop) - goes until they get it right D. Overflow: when you add to a number and it gets too big for its type int i; double d; while(true) { i++; d++; } - after a LONG time, these will overflow - int hits ~2 billion, wraps to negative ~2 billion (surprise!) - double hits ~1.8^308 and becomes "Infinity" (if you wondered) E. Another loop: do-while (same idea, details different) - text-based menu where entering 0 means stop game int option; do { option = getInt(); switch(option) {...} // do the menu option } while (option > 0); - exactly what code does; draw diagram for it - this is a posttest loop (test comes after body goes once) - while is a pretest loop (test comes before body ever goes) 4) Summary - while loops, do-while loops, infinite loops, off-by-one errors *******************************************************************************