1 / 27

Looping with While and For

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

mead
Download Presentation

Looping with While and For

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Looping with While and For • Instructor Nash • Readings: Savitch, Chapter 3 (Section 3) • CSS 161 V2.0

  2. 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

  3. Loop Flowchart (For and While) ? True Code Block False

  4. Basic If Flowchart ? True Code Block False

  5. While Form • <loop variable declaration and initialization> • while( <loop continuation test> ) { • <statement> • … • <statement> • <increment or decrement statement> • }

  6. 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!

  7. 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 • }

  8. 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!

  9. 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: • {<,>, ==, !=, <=, >=}

  10. 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

  11. 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’)

  12. 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

  13. 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

  14. 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

  15. Truth Table for Not • p !p • True False • False True

  16. 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

  17. 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:

  18. 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!

  19. 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; • }

  20. 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++) {…}

  21. 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

  22. 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(); • }

  23. File Processing Example • Some OSes use a specific value to indicate end-of-file • Called an EOF sentinel • while( ! currentFile.isEOF() ) { • readNextLine(); • }

  24. While Loop for Smallest Divisor • intsmallestDivisor = 2; //why 2? • while( number % smallestDivisor != 0) • smallestDivisor++;

  25. 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!

  26. 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

  27. 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! • } • }

More Related