instructor nash readings: savitch, chapter 3 (section 3) css 161 v2.0

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

Post on 19-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

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

Looping with While and For

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

Loops in General

Loop Flowchart (For and While)

? Code BlockTrue

False

Basic If Flowchart

? Code BlockTrue

False

<loop variable declaration and initialization>

while( <loop continuation test> ) {◦ <statement>◦ …◦ <statement>◦ <increment or decrement statement>

}

While 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!

For Form

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

}

While and For

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 Loop

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:

{<,>, ==, !=, <=, >=}

The While “Question”

{<,>, ==, !=, <=, >=} 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

Relational Operators -> {true, false}

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

Simple and Compound Expressions

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

Logical Operators

p q p && q True True True False True False True False False False False False

//note that False AND X is always False◦ Useful for short circuit evaluation later

Truth Table for AND

p q p || q True True True False True True True False True False False False

//Note that True OR X is always True◦ Useful for short-circuit evaluation

Truth Table for OR

p !p True False False True

Truth Table for Not

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:

Short-Circuit Evaluation

◦ 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!

More on Short-Circuit

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; }

Definite 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();

} int someRandInt = (int) Math.rand() * 100 for( int r = 0; r < someRandInt; r++) {…}

Indefinite Looping

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

Indefinite Looping and 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();

}

Looping with Sentinels

Some OSes use a specific value to indicate end-of-file◦ Called an EOF sentinel

while( ! currentFile.isEOF() ) {◦ readNextLine();

}

File Processing Example

int smallestDivisor = 2; //why 2? while( number % smallestDivisor != 0)

◦ smallestDivisor++;

While Loop for Smallest Divisor

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!

Infinite 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 and “Forever” Loops

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!

◦ } }

Break == Get Me Out of This Block