LECTURE NOTES OCTOBER 11 2004 ASSIGNMENTS Fri 10/15 CodeLab #6 Mon 10/18 Assignment 2 SHORTHAND ASSIGNMENT OPERATORS Why? - common to do an operation to a variable, and assign it back to itself What? - shorthand assignment operators How? = +=, -=, *=, /=, %= What? - shorthand assignment precedence How? - lower than arithmetic operators THE WHILE STATEMENT Why? - repeatedly execute a block of code until some condition is true What? - type of control statement - *repetition/loop statement* - while statement How? - syntax while ( ) What? - using statements inside a loop How? - can be single or compound (requires braces) - *loop body* What? - control diagram of while statement How? - diamond for loop condition - rectangle for loop body - arrow into diamond - true arrow from diamond to rectangle - arrow from rectangle to above diamond - false arrow out of diamond TYPES OF WHILE LOOPS Why? - execute a loop a specific number of times What? - *count-controlled loop* Why? - execute a loop until some special value is encountered What? - *sentinel-controlled loop* USING WHILE LOOPS Why? - improving the user interface How? - handle invalid input - let the user input a value until it is correct Why? - have to get some initial input to start with What? - *priming read* COMMON LOOP ERRORS What? - *infinite loop* Why? - usually arithmetic performed during an infinite loop What? - *overflow error* Why? - overflow error What? - particular way that Java handles How? - reals: assigns a reserved value representing infinity - integers: value wraps around What? - using real numbers for testing and increment Why? - real numbers are infinite - the computer can only approximate this - comparisons and operations can appear non-deterministic What? - handling real number imprecision How? - avoid using them when require test for equality Why? - think too quickly What? - *off-by-one error* What? - make a loop execute N times How? - initialize the counter to 0 and use < N - initialize the counter to 1 and use <= N PRACTICE PROBLEMS 1. Identify errors: a. while (x < 1 && x > 10) { a = b; } b. while (a == b) ; { a = b; x = y; } 2. Write a while statement to compute the following sum. 1 + 2 + 3 + ... + 100 int count = 0, sum = 0; while (count < 100) { count++; sum += count; }