cse 1301 lecture 6b more repetition figures from lewis, “c# software solutions”, addison wesley...

49
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

Upload: merryl-morris

Post on 18-Dec-2015

215 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301

Lecture 6B

More Repetition

Figures from Lewis, “C# Software Solutions”, Addison Wesley

Briana B. Morrison

Page 2: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-2

Overview• Infinite Loops (again)

• Loop patterns (common tasks)

• Sentinel loops

• Nested Loops

• Examples

Page 3: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-3

What is the output?int count;

for ( count = 0 ; count < 10 ; count++ )

{

C.O.W(“*”) ;

}

Page 4: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-4

OUTPUT

**********

NOTE: the 10 asterisks are all on one line. Why?

Page 5: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-5

What’s the output from this loop?

int count;

for (count = 0; count < 10; count++) ;{

C.O.W(“*”);

}

Page 6: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-6

• no output from the for loop! Why?• the ; right after the ( ) means that the body

statement is a null statement• in general, the body of the for loop is whatever

statement immediately follows the ( )• that statement can be a single statement, a

block, or a null statement • actually, the code outputs one * after the loop

completes its counting to 10

OUTPUT

Page 7: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-7

int i = 0;

while ( i < 10 );

{

i++;

}

What does this loop do?

Page 8: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-8

• INFINITE LOOP!

• The semicolon indicates an empty loop body; i++ is never executed because it is not part of the loop body, so the condition is always true.

• Avoid putting a semicolon after the condition of a while loop. Doing so creates an empty loop body and could result in an endless loop.

Page 9: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-9

The Endless Loop• also called an infinite loop• If the loop condition never evaluates to false, the

loop body is executed continuously, without end• If the loop body has no output, the endless loop

makes the computer appear to hang.• If the loop body produces output, the endless

loop results in that output being repeatedly written without end.

• Aborting the program will interrupt the endless loop.

Page 10: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-10

Looping Techniques• There are standard patterns and

techniques for performing these common operations:– Accumulation– Counting Items– Finding an Average– Finding Maximum or Minimum Values

Page 11: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-11

Accumulation• Approach: the running total

– We start by initializing a total variable to 0.– Each time we read a value, we add it to the

total.– When we have no more values to read, the

total is complete.

• Note that this is the same pattern used by the grocery cashier.

Page 12: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-12

Accumulation Pseudocodeset total to 0 // very important!

read a number // priming read

while ( number is not the sentinel value )

{

add the number to total

read the next number // update read

}

output the total

Page 13: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-13

• Forgetting to initialize the total variable to 0 before beginning the loop will produce incorrect results.

Page 14: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-14

Counting Items• Approach: the running count

– We start by initializing a count variable to 0.– Each time we read a value, we check

whether that value meets the criteria as something we want to count. If so, we increment the count variable by 1.

– When we are finishing reading values, the count is complete.

Page 15: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-15

Counting Items Pseudocodeset count to 0 // very important!!

read input // priming read

while ( input is not the sentinel value )

{

if ( input is what we want to count ) add 1 to count

read the next input // update read

}

output count

Page 16: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-16

• Forgetting to initialize the count variable to 0 before beginning the loop will produce incorrect results.

Page 17: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-17

Calculating an Average• Approach: combine accumulation and

counting• We start by initializing a total variable and

count variable to 0. • Each time we read an item, we add its

value to the total variable and increment the count variable

• When we have no more items to read, we calculate the average by dividing the total by the count of items.

Page 18: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-18

Calculating an Average Pseudocode set total to 0 set count to 0 read a number while ( number is not the sentinel value ) { add the number to total

add 1 to the count  read the next number}set average to total / countaverage = (count==0)? 0 : (double) total / count;

output the average

Page 19: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-19

• Forgetting to check whether the denominator is 0 before performing division is a logic error.

Page 20: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-20

Correct Calculation • Remember that if we declare total and count as

integers, then average will be calculated using integer division, which truncates the remainder.

• To get a floating-point average, we need to type cast one of the variables (either total or count) to a double or a float to force the division to be performed as floating point.

• Example: double average = (double) ( total ) / count;

Page 21: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-21

Finding Maximum/Minimum Values• Approach: the running maximum or minimum• For the maximum (minimum is similar):

– Read the first item and save its value as the current maximum

– Each time we read a new value, we compare it to the current maximum.

• If the new value is greater than the current maximum, we replace the current maximum with the new value.

– When we have no more items to read, the current maximum is the maximum for all values.

Page 22: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-22

• Initializing a maximum or a minimum to an arbitrary value, such as 0 or 100, is a logic error and could result in incorrect results.

• For example, if we initialize the maximum to 0 and all the values read are less than 0, then we will incorrectly report 0 as the maximum.

• Similarly, if we initialize the minimum to 0 and all the values read are greater than 0, then we will incorrectly report 0 as the minimum.

Page 23: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-23

A Sentinel-controlled Loop• requires a “priming read” (initialization)--this

means you read one set of data before the while

• test if not sentinel value• update is another readSentinel values:

– same data type as value read– must tell user the sentinel value– cannot be a valid data value

Page 24: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-24

Sentinel-Controlled while Loopinitialize variables// priming readread the first data item while ( item is not the sentinel value ) { process the item // update read read the next data item }report the results

Page 25: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-25

• Omitting the update read may result in an endless loop.

• Example: C.O.W( "Enter a value > " ); int input = scan.nextInt( ); while ( input != 10 ) // 10 is sentinel value { C.O.Wln( input ); }

• If the value entered for input is not 10, this is an endless loop because we never read a new value for input. Thus, the condition always evaluates to true.

Page 26: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-26

• Omitting the priming read can lead to incorrect results.

• Example: int input, count = 0; while ( input != 10 ) // 10 is sentinel value { C.O.W( "Enter an integer > " ); input = scan.nextInt( ); count++; } C.O.Wln( "Count is " + count );

• If the user enters the values 20 30 10, then the output will be "Count is 3", which is incorrect. We should not process the sentinel value.

Page 27: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-27

Do not check for the sentinel value inside a while loop. Let the while loop condition detect the sentinel value.

Page 28: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-28

Constructing Loop Conditions• The loop body is executed as long as the

loop condition evaluates to true• So if we want to stop executing the loop

when the sentinel value is read, the loop condition has to check that the value is NOT the sentinel

• Thus, the loop continuation condition is the inverse of the loop termination condition.

Page 29: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-29

Example: Find Sum of 5 Integers set total to 0 for i = 1 to 5 by 1

{

read integer

add integer to total

}

print the total

Page 30: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-30

Update Increment Can Be > 1

• Print the even numbers from 0 to 20

set output to an empty String

for i = 0 to 20 by 2

{

append i and a space to output

}

print the output String

Page 31: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-31

for (init; expr1; expr2)statement;

• init statement can be null; expr2 is optionalfor ( ; inputval != 999; )

inputval = scan.nextInt();• expr1 optional, true assumed

for ( ; ; )C.O.Wln( “Hi”);

• init can be a declarationfor (int i = 0; i < 10; i++)//local scope

For Loop Rules

Page 32: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-32

Loop Control Variable Scope• When a loop control variable is declared

inside the for loop header, it cannot be referenced after the loop

for ( int i = 0; i < 3; i++ ) {

C.O.Wln( i ); // ok

}

C.O.Wln( i ); // error: i undefined

Page 33: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-33

To Reference i After the Loop int i; // declare i before loop

for ( i = 0; i < 3; i++ )

{

C.O.Wln( i );

}

C.O.Wln( i ); // ok

Page 34: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-34

Testing for Loops• An important test for for loops is that the

starting and ending values of the loop variable are set correctly.

• For example, to iterate 5 times, use this header:

for ( int i = 0; i < 5; i++ )

or this header:

for ( int i = 1; i <= 5; i++ )

Page 35: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-35

Nested Loops• Loops can be nested inside other loops;

that is, the body of one loop can contain another loop.

• A while loop can be nested inside another while loop or a for loop can be nested inside another for loop.

• A for loop can be nested inside a while loop and a while loop can be nested inside a for loop.

Page 36: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-36

initialize outer loop

while ( outer loop condition )

{ . . .

initialize inner loop

while ( inner loop condition )

{

inner loop processing and update

}

. . .}

Pattern of a Nested Loop

Page 37: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-37

To design a nested loop • begin with outer loop

• when you get to where the inner loop appears, make it a separate module and come back to its design later

Page 38: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-38

// print heading C.O.Wln("i \t j");

for (int i = 0; i < 4; i++) { C.O.Wln( "Outer " + i); for (int j = 0; j < i; j++)

C.O.Wln( " Inner \t" + j); } // end for - outer loop

What’s the Output?

Page 39: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-39

Nested for Loop Execution• Inner loop executes all its iterations for

each single iteration of the outer loop

• Example: how can we print this?

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

Page 40: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-40

Analysis• The highest number we print is the

same as the line number. for line = 1 to 5 by 1 { for number = 1 to line by 1 { print number and a space } print a new line }

Page 41: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-41

• Now let’s work some more loop examples….

Page 42: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-42

Test YourselfHow many times is the loop body below repeated?What is printed during each repetition of the loop body?

x = 3;count = 0;while (count < 3){ x = x * x; C.O.Wln(x); count++;} //end while

Page 43: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-43

Test Yourself

The following for loop is intended to display the values of i from 1 to 10. But the loop does not work correctly. Explain what the problem is and describe how to correct it.

for (int i = 0; i < 10; i++)C.O.Wln( i++);

Write a loop to add all the odd integers between 1 and n.

Page 44: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-44

Test YourselfWhat output values are displayed by the loop below for a data value of 5?

C.O.Wln( “Enter an integer “); x = int.Parse(kb.ReadLine()); product = x; count = 0; while (count < 4) {

C.O.Wln( product );product = product * x;count++;

} // end while C.O.Wln(“End of loop “ + count + “ “ + product);

Page 45: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-45

Test YourselfWhat is the least number of times that the body of a while loop may be executed?

What is displayed by the segment:sum = 0;while (sum < 100)

sum += 5;C.O.Wln( sum );

Rewrite the loop so that it prints all multiples of 5 from 0 through 100, inclusive.

Your young cousin is learning the binary number system and has asked you to write a program that displays all powers of 2 that are less than a certain value (say, 10,000).

Page 46: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-46

Test Yourself

Write a flag-controlled loop that continues to read pairs of integers until it reads a pair with the property that the first integer in the pair is evenly divisible by the second.

Page 47: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-47

What does the while statement below display? Rewrite it as a for statement.

num = 10;while (num <= 100){

C.O.Wln( num );num += 10;

} // end while

What does the for statement below display? Rewrite it as a do-while statement.

for (n = 3; n > 0; n--)C.O.Wln( n + “ squared is “ +

Math.pow (n, 2));

Test Yourself

Page 48: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-48

What is displayed by the following program segments? (Assume m is 3 and n is 5.)

for (int i = 0; i < n; i++){

for (int j = 0; j < i; j++)C.O.W( “*”);

C.O.Wln( );} // end for i

for (int i = m; i > 0; i--){

for (int j = n; j > 0; j--)C.O.W( “*”);

C.O.Wln( );} // end for i

Page 49: CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison

CSE 1301 6B-49

Write the nested loops that cause the output below to print.

11 22 32 3 42 31 2 1