270 likes | 405 Views
Looping with While and For. Instructor Nash Readings: Savitch , Chapter 3 (Section 3) CSS 161 V2.0. Loops in General. Have: A loop variable (integer) A starting or initial value A final or terminal value An increment or decrement And conceptually: Should do some work each iteration
E N D
Looping with While and For • Instructor Nash • Readings: Savitch, Chapter 3 (Section 3) • CSS 161 V2.0
Loops in General • Have: • A loop variable (integer) • A starting or initial value • A final or terminal value • An increment or decrement • And conceptually: • Should do some work each iteration • I.e., progress the state of the loop • Should be moving from start to finish
Loop Flowchart (For and While) ? True Code Block False
Basic If Flowchart ? True Code Block False
While Form • <loop variable declaration and initialization> • while( <loop continuation test> ) { • <statement> • … • <statement> • <increment or decrement statement> • }
For Form • For( expression1; expression2; expression3) { • //body • } • Exp1: Loop variable declaration and initial value • Exp2: Loop continuation test and terminal value • Exp3: Increment or decrement • Should move from initial to terminal value, else infinite!
While and For • Exp1: Loop variable declaration and starting value • Exp2: Loop continuation test and terminal value • Exp3: increment or decrement • <Exp1> • while( <Exp2> ) { • //body • <Exp3> • } • for(<Exp1>;<Exp2>;<Exp3>){ • //body • }
The While Loop • Similar to a “For”, but less centralized • Most “For” loops can be rewritten as a “While” and vice versa • The “For” header combines: • Loop variable declaration and initialization • A loop test • Thus a terminal value • An increment that brings the loop variable closer to the terminal value • Note that, just like a For, if the test is initially false, we skip the whole loop!
The While “Question” • A While loop continues to execute while the condition remains true • For example, we might look while x < 6 • To build such a “loop test” or “question”… • We’re really building a boolean expression • This will evaluate to {true, false} • To do so, use a relational operator: • {<,>, ==, !=, <=, >=}
Relational Operators -> {true, false} • {<,>, ==, !=, <=, >=} • Used to relate two quantities or objects • Posit questions such as: • Is x less than y? • Are a and b equal? • Are y and z not equal? • Is GPA greater than a 3.0? • Note: we may need to combine two simple boolean expressions
Simple and Compound Expressions • Frequently, we’ll need to group together multiple simple expressions into a compound expression: • if( digit >= 0 && digit <= 9 ) • if( digit > 0 && digit % 2 == 0) • We can create these using Logical Operators • {AND, OR, NOT} //in java, {&&, ||, !} letterGrade >= ‘a’ & letterGrade <=‘f’ & letterGrade != ‘e’)
Logical Operators • Used to make compound boolean expressions • Loop tests and If tests • && is AND • conjunction • || is OR • disjunction • ! is NOT • negation • //note: above implies short-circuit evaluation • //below implies no short-circuit evaluation • & is AND • | is OR
Truth Table for AND • p q p && q • True TrueTrue • False True False • True False False • False FalseFalse • //note that False AND X is always False • Useful for short circuit evaluation later
Truth Table for OR • p q p || q • True TrueTrue • False True True • True False True • False FalseFalse • //Note that True OR X is always True • Useful for short-circuit evaluation
Truth Table for Not • p !p • True False • False True
Short-Circuit Evaluation • Consider the code to stop at the first space: • int stop = 0; • while(s.charAt(stop) != ‘ ‘ && stop < s.length() ) { • stop++; • } • When the above code gets to the last letter in the string “foo”, what will happen? • stop will be incremented, and the next call to charAt will throw an exception
Short-Circuit Evaluation • Defn: If we know the boolean result from our first computation, don’t do any more computations. • TRUE OR X -> TRUE • FALSE AND Y -> FALSE • Previous example, consider swapping the order and relying on short-circuiting:
More on Short-Circuit • int stop = 0; • while(stop < s.length() && s.charAt(stop) != ‘ ‘ ) { • stop++; • } • Now, if we ever go over the length of the string, the first part of the compound expression above will evaluate to false, and we won’t execute the charAt!
Definite Looping • The number of times to loop is known in advance • These are “static” loops – happens the same amount each time, every time. • for(int r = 0; r < 10; r++) • int number = 0; //problem here? • while( number <= 512 ) { • number *= 2; • }
Indefinite Looping • We can’t tell just by observing the code how many times these loops will iterate • These loops may change their behaviour based on: • User input • Date and time • A (pseudo)random number • while( isLoggedIn == false) { • isLoggedIn = QueryUsernamePassword(); • } • intsomeRandInt = (int) Math.rand() * 100 • for( int r = 0; r < someRandInt; r++) {…}
Indefinite Looping and Sentinels • Sometimes, we ask the user to control our loops • For example, consider a grade averaging algorithm • We could ask ahead of time “how many grades?” • Or, we could use a dummy or Sentinel value • These must be chosen with care so as to not confuse with valid user input – in this example, a quiz score. • “-1” is a good dummy value here, since its not a legal score
Looping with Sentinels • Defn: A sentinel is a unique value that signals the end of input. • To be a sentinel value, you must be distinguishable from “normal” or expected input • Also, you shouldn’t factor in the sentinel to your calculations (see below) • Classic “loop-and-a-half” problem • nextGrade = getGradeFromUser(); • while( nextGrade != -1 ) { • sum += nextGrade; • nextGrade = getGradeFromUser(); • }
File Processing Example • Some OSes use a specific value to indicate end-of-file • Called an EOF sentinel • while( ! currentFile.isEOF() ) { • readNextLine(); • }
While Loop for Smallest Divisor • intsmallestDivisor = 2; //why 2? • while( number % smallestDivisor != 0) • smallestDivisor++;
Infinite Loops • while( someNumber < 100 ) { • //body • //needs a statement like “someNumber = …;“ • } • If someNumber starts less than 100, and • The body never updates or changes this variable • We will loop forever! • Key idea: if your loop test hinges on a variable, you must update that variable inside the loop body • If the loop variable never changes and the condition is initially true, it will always be true – stuck in stasis!
Break and “Forever” Loops • Ignore the concept of “Forever” looping • Says “optional” in the text • Also, be wary of “breaking” too much • Read page 301 for history, but I wonder about some of the research and how it’s evaluated • Djikstra is awesome
Break == Get Me Out of This Block • You can “break;” out of a loop • Similar to “return” for functions • You can break out of loops nested in other loops • Usually, use this only for performance • ForEach( element of 100,000,000 ) { • If( foundIt ) { • index = currentIndex; • break; //don’t inspect the rest! • } • }