CSC153 2004S, Class 33: Loops Admin: * Cool convo tomorrow * No homework yet * Lab-based day * Add the following line to the end of your .bashrc (e.g., with "gedit .bashrc") export PATH="$PATH:/usr/java/j2sdk1.4.1_03/bin" and then open a new terminal window. From now on, you can use javac and java without doing the extra stuff Overview: * Lab: J5.1-J5.3 and (maybe) J5.7 Observation: Many algorithms require repetition * One good mechanism for repetition: Recursion * Another less-good mechanism for repetition: Goto * Some folks dislike recursion * In the early 1960's, some computer scientists designed new ways of referring to repetition "looping structures" * Three (more or less) basic looping structures * For loops: Fixed number of repetitions, usually with an associated counter variable * While loops: Indeterminate number of repetions, with the test before the fisrt repetition * Repeat loops (Do loops): Interminate number of repetions > 0, with the test after the first repetion In Java (and C, and C++, and most other C-based languages), While loops: while (TEST) { BODY } Meaning: 1. Evaluate test 2. If test holds, evaluate BODY and go to line 1. 3. Otherwise, "exit the loop"; Go on to the subsequent statement For loops: for(INITIALIZE; TEST; INCREMENT) { BODY } Meaning INITIALIZE; while (TEST) { BODY; INCREMENT; } Most common for loops for (VAR = INITIAL; VAR < TERMINATE; ++VAR) { BODY } "Real" C programmers prefer that their for loops not have bodies Programmers who want others to read and use their code try to write more readable code. I never remember the repeat-like loops do { BODY } while (TEST) Nearly equivalent to BODY while (TEST) { BODY } Applets in Java * Need a "draw" method that draws on the screen. * Need an accompanying HTML file to set up the size of the screen * Run with appletviewer