control structures ii repetition (loops). why is repetition needed? how can you solve the following...

31
Control Structures II Repetition (Loops)

Upload: joseph-turner

Post on 04-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Control Structures II

Repetition (Loops)

Page 2: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Why Is Repetition Needed?

How can you solve the following problem:•What is the sum of all the numbers from 1

to 100.•The answer will be

1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100.

Page 3: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Why Is Repetition Needed?

Here’s some sample Java code:int sum=0;sum = sum+1;sum = sum +2;sum = sum +3;sum = sum +4;…sum = sum +99;sum = sum +100;System.out.println(“The sum from 1 to 100 = “

+sum);

Page 4: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

This solution has problems:•It would take a long time to type in. •There is a high risk of making an error

while typing it in.•It doesn’t easily scale. This may work for

100 numbers but how would you handle having to add from 1 to a 1000? Or to 1000000?Or to 1000000000?

Why Is Repetition Needed?

Page 5: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Why Is Repetition Needed?The Algorithm

1. Create a variable to hold the sum.2. Initialize the sum to zero.3. Create a variable to hold a counter from 1 to 100.4. Initialize the counter to 1.5. While the counter is less-than-or-equal to 1006. add the counter to the sum7. add one to the counter8. Now repeat9. Print the sum

Page 6: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

We can use pseudo-code:sum = 0count = 1loop while count <= 100 sum = sum + count count++endloopprint sum

Why Is Repetition Needed?

Page 7: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Why Is Repetition Needed?loop while condition <body>endloop

• This pseudo-code means: before executing the statements in the body, evaluate the condition. If the condition is true then execute the body once.

• Once you have executed the body statements once, go back to the loop condition and re-evaluate it. If it is true, execute the body code again. If the condition is not true then the body will not be executed!

Page 8: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

8

The while Looping (Repetition) Structure

•Infinite loop: is a loop that continues to execute endlessly.

•So, expression is always true in an infinite loop.

•Statements must change value of expression to false.

Page 9: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

i = 0loop while (i <= 20)

print(i)i = i + 5

end loop

Examplestart

i = 0

i <= 20

end

No

i = i + 5

Print i

Yes0i

Output

05101520

5

10

15

20

25 What will happen if you omit (i= i + 5) ?

Page 10: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

While Loop Types

•Counter-Controlled Loop•Sentinel-Controlled Loop•Flag-Controlled Loop

Page 11: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Counter-Controlled Loop• Used when exact number of data or entry

pieces is known.• General form:N = …counter = 0Loop while (counter < N) . . . counter = counter + 1 . . .End loop

N = …

counter = 0

Read N

or

counter < N

do operation

counter = counter + 1

No

Yes

(1) Initialization

stmt.

(3) Update stmt.

(2) Loop condition

Page 12: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Example

•Write a program to allow the user to enter a set of integer numbers, then print the sum of these numbers.

Start ProgramRead setSizecounter = 0sum = 0Loop while (counter < setSize)

Read numbersum = sum + numbercounter = counter + 1

End loopPrint sum

End Program

Page 13: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

start

Start ProgramRead setSizecounter = 0sum = 0Loop while (counter < setSize)

Read numbersum = sum + numbercounter = counter + 1

End loopPrint Sum

End Program

counter = counter + 1

Read setSize

counter = 0

sum = 0

counter < setSize

YesRead

number

sum = sum + numberOutput

3110415

1

2

3

0counter

3setSize

0sum

No

end

Print sum

1

11

15

1number

10

4

Page 14: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Counter-Controlled Loop: Another way for expressing it

While loop

For loop

N = …counter = 0Loop while (counter < N) . .

counter = counter + 1End loop

N = …For(counter = 1, counter <= N, counter = counter + 1) . .

End For

Initialization Condition Increment \ Decrement

Step 1counter = 1 to N

Page 15: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Counter-Controlled Loop –For Loop

N = …

counter = 1

Read N

or

counter <= N

do operation

counter = counter + 1

No

Yes

N = …Read

Nor

do operation

Next counter

Can be simplifie

d to:

For counter = 1 to N, step 1

The for loop does not have a standard flowcharting method and you will find it done in different ways.

Page 16: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Example

1. Write down an algorithm and draw a flowchart to find and print the largest of N (N can be any number) positive numbers. Read numbers one by one.

2. Verify your result by tracing the developed algorithm. (Assume N to be 4 and the following set to be the numbers {5 2 6 1})

Page 17: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

start

Solution

Start ProgramRead Nmax = 0For(counter = 1 to N, step

1)Read numberif (number > max)

max = number

End ForPrint max

End Program

counter <= N

max = 0

Read N

counter = 1

YesRead number

No

Print max

number > max

end

No

max = number

Yes

counter = counter + 1

(1)

Page 18: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

start

counter <= N

max = 0

Read N

counter = 1

YesRead number

No

Print max

number > max

end

No

max = number

Yes

counter = counter + 1

(2) • Trace the developed algorithm. • Assume N to be 4 and the following set

to be the numbers {5 2 6 1}

4N

0max 1

counter 5

number

5 2 2

3 66

4 1

5

Print max 6

Page 19: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Sentinel-Controlled Loop• Used when exact number of entry pieces is

unknown, but last entry (special/sentinel value) is known.

• The idea of a sentinel controlled loop is that there is a special value (the "sentinel") that is used to say when the loop is done.

• General form:Input the first data item into variable

Loop while (variable != sentinel) .

. . input a data item into variable; . . .End loop

Page 20: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Example•Write a program that adds up a list of

positive numbers entered by the user from the keyboard, then prints the result.

•What is the number of iterations ??▫Unknown

•Since the input are positive integers, we can use (-1) as the sentinel.

•Example of user input: 1 3 6 4 9 12 3 5 -1

Page 21: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

SolutionStart Program

sum = 0Read numberloop while (number != -1)

sum = sum + numberRead number

End loopPrint sum

End Program

start

sum = 0

Read number

No

Print sum

end

Read number

sum= sum+ number

Yes

number != -1

0sum 5

number

5 2

37

-1

Input523-1

523-1

10 Print sum 10

Page 22: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Flag-Controlled Loop• A flag is a boolean variable, used to indicate

whether or not a desired situation has occurred ▫ A value of FALSE indicates that the desired event

has not yet occurred ▫ TRUE indicates that it has occurred

• General form:boolean found = falseLoop while (!found) . .

if (expression) found = true . .

End loop

Initialization

Testing

Updating

Page 23: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Example: Number Guessing Game• Write a program that generates a random number

in the range 0..100.• Then the user tries to guess the number.• If the user guessed the number correctly, then print

the message “You guessed the number correctly !”.• Otherwise:

▫If the guessed number is less than the random number, print message “Your guess is lower than the number”.

▫Otherwise: print message “Your guess is higher than the number”.

▫The user enters another number.• The user guesses until he\she enters the correct

number.

Page 24: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

SolutionStart ProgramrandomNumber = … will be discussed laterguessedRight = falseloop while (not guessedRight)

Read guessif (guess = randomNumber)

guessedRight = truePrint “You guessed the number correctly !”

elseif (guess < randomNumber)

Print “Your guess is lower than the number”

elsePrint “Your guess is higher than the

number”End loop

End Program

Page 25: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Solution

start

randomNumber = …

Read guessNo

end

Yes NotguessedRig

ht

guessedRight = false

guessedRight = true

guess = randomNumb

er

Yes

No

Print “Correct Guess”

guess < randomNumb

er

Print “Guess

is Lower”

Print “Guess

is Higher”

No

Yes

Page 26: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

The do…while Loop

•Form:do statement(s)while (expression)

•Statements are executed first and then expression is evaluated.

•Statements are executed at least once and then continued if expression is true.

Page 27: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Difference

do…while Loop

while Loop

for Loop

Page 28: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

ExampleSECRET_CODE = 1234

doPrint "Type the secret code number to enter."Read code

while (code!=SECRET_CODE)

Print "Well done, you can now enter"

SECRET_CODE = 1234

NoPrint msg

Print input msg

Read code

Yescode != SECRET_CODE

Page 29: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Nested loop: loop in loop

Example: Print the following using loops.

***************

5 rows :

Row 1 1 starRow 2 2 stars…Row 5 5 stars

We need a loop for the rowsWe need loops for columnsThe number of stars in a row is equal to the row#

Need nested loop

Since the # of iterations are known for loops

Page 30: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Nested loop: loop in loopSolution:For (i = 1 to 5, step 1) For (j = 1 to i, step 1) print(" *")

End For move cursor to next lineEnd For

Output:***************

Page 31: Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1

Chapter Summary•Looping mechanisms:

▫Counter-controlled while loop for loop

▫Sentinel-controlled while loop▫Flag-controlled while loop▫do…while loop

•Nested control structures