Presentation is loading. Please wait.

Presentation is loading. Please wait.

 Instructor Nash  Readings: Savitch, Chapter 3 (Section 3)  CSS 161 V2.0.

Similar presentations


Presentation on theme: " Instructor Nash  Readings: Savitch, Chapter 3 (Section 3)  CSS 161 V2.0."— Presentation transcript:

1  Instructor Nash  Readings: Savitch, Chapter 3 (Section 3)  CSS 161 V2.0

2  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 ? Code Block True False

4 ? Code Block True False

5   while( ) { ◦ ◦ … ◦  }

6  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  Exp1: Loop variable declaration and starting value  Exp2: Loop continuation test and terminal value  Exp3: increment or decrement   while( ) { ◦ //body ◦  }  for( ; ; ){ ◦ //body  }

8  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  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  {, ==, !=, =}  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  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  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  pqp && q  TrueTrueTrue  FalseTrueFalse  TrueFalseFalse  FalseFalseFalse  //note that False AND X is always False ◦ Useful for short circuit evaluation later

14  pqp || q  TrueTrueTrue  FalseTrueTrue  TrueFalseTrue  FalseFalseFalse  //Note that True OR X is always True ◦ Useful for short-circuit evaluation

15  p!p  True False  FalseTrue

16  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  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 ◦ 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  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  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();  }  int someRandInt = (int) Math.rand() * 100  for( int r = 0; r < someRandInt; r++) {…}

21  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  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  Some OSes use a specific value to indicate end-of-file ◦ Called an EOF sentinel  while( ! currentFile.isEOF() ) { ◦ readNextLine();  }

24  int smallestDivisor = 2; //why 2?  while( number % smallestDivisor != 0) ◦ smallestDivisor++;

25  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  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  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! ◦ }  }


Download ppt " Instructor Nash  Readings: Savitch, Chapter 3 (Section 3)  CSS 161 V2.0."

Similar presentations


Ads by Google