CSC152 2005S, Class 19: Loops Admin: * Sam and Cassie absent after today. Arjun and Eryn (and others?) teach Friday. * Exam due a week from Friday. Distributed Friday or Sunday (depending on Interenet access). Overview: * What are loops? * Three basic looping structures. * Lab. Sometimes we need to do things again and again and again * Example: The opening screen for this computer needs to prompt for my account and password until I enter a valid pair. * Example: Naive exponentiation 5*5*5*5... * Although we can express all of these forms of repetition with recursion, in many cases it is more "natural" to express it in other ways. * When sam talked about the prompt: repeat prompt for username and password until a valid username and password are entered * To compute 5^20 multiply by 5 20 times * Many programming languages provide control structures for indefinite repetition (repeat) and definite repetition (as in the multiply) Easiest form of indefinite repetition: while loop Form: while (TEST) { BODY } NEXT Meaning: 1. Evaluate the TEST. If it holds, a. Execute the BODY. b. Go back to step 1. 2. If the test does not hold, go on to the next statment Alternate form of indefinite repeittion: do loop do { BODY } while (TEST); 1. Execute the BODY 2. Evaluate the TEST. If it holds, go back to step 1. 3. If the TEST doesn't hold, done with the loop Definite repetition: For loop, simple form for (int i = START_VALUE; i < END_VALUE; i=i+1) { BODY } Execute BODY for each value of i between START_VALUE (inclusive) and END_VALUE (exclusive) To print the squares of all nubmers from zero to ten for (int i = 0; i < 11; i=i+1) { pen.println(i*i); } To compute 5 to the 20th power int result = 1; for (int i = 0; i < 20; i=i+1) { result = result*5; } for(INIT; TEST; INCREMENT) { BODY } shorthand for INIT; while (TEST) { BODY; INCREMENT: } for (int i = 0; i < 20; i=i+1) { result = result*5; } int i = 0; while (i < 20) { result = result*5; i=i+1; } Questions and comments from the lab