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

## Presentation on theme: "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."— Presentation transcript:

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 to 100. The answer will be 1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100.

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

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?

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 100 6. add the counter to the sum 7. add one to the counter 8.Now repeat 9.Print the sum

We can use pseudo-code: sum = 0 count = 1 loop while count <= 100 sum = sum + count count++ endloop print sum Why Is Repetition Needed?

loop while condition 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!

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.

i = 0 loop while (i <= 20) print(i) i = i + 5 end loop Example start i = 0 i <= 20 end No i = i + 5 Print i Yes 0 0 i Output 0 5 10 15 20 5 5 10 15 20 25 What will happen if you omit ( i= i + 5) ?

While Loop Types Counter-Controlled Loop Sentinel-Controlled Loop Flag-Controlled Loop

Counter-Controlled Loop Used when exact number of data or entry pieces is known. General form: N = … counter = 0 Loop 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

Example Write a program to allow the user to enter a set of integer numbers, then print the sum of these numbers. Start Program Read setSize counter = 0 sum = 0 Loop while (counter < setSize) Read number sum = sum + number counter = counter + 1 End loop Print sum End Program

start Start Program Read setSize counter = 0 sum = 0 Loop while (counter < setSize) Read number sum = sum + number counter = counter + 1 End loop Print Sum End Program counter = counter + 1 Read setSize counter = 0 sum = 0 counter < setSize Yes Read number sum = sum + number Output 3 1 10 4 15 1 1 2 2 3 3 0 0 counter 3 3 setSize 0 0 sum No end Print sum 1 1 11 15 1 1 number 10 4 4

Counter-Controlled Loop: Another way for expressing it While loop For loop N = … counter = 0 Loop while (counter < N). counter = counter + 1 End loop N = … For(counter = 1, counter <= N, counter = counter + 1).. End For InitializationConditionIncrement \ Decrement Step 1counter = 1 to N

Counter-Controlled Loop –For Loop N = … counter = 1 Read N or counter <= N do operation counter = counter + 1 No Yes N = … Read N or do operation Next counter Can be simplified 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.

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

start Solution Start Program Read N max = 0 For(counter = 1 to N, step 1) Read number if (number > max) max = number End For Print max End Program counter <= N max = 0 Read N counter = 1 Yes Read number No Print max number > max end No max = number Yes counter = counter + 1 (1)

start counter <= N max = 0 Read N counter = 1 Yes Read 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} 4 4 N 0 0 max 1 1 counter 5 5 number 5 5 2 2 2 2 3 3 6 6 6 6 4 4 1 1 5 5 Print max  6

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

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

Solution Start Program sum = 0 Read number loop while (number != -1) sum = sum + number Read number End loop Print sum End Program start sum = 0 Read number No Print sum end Read number sum= sum+ number Yes number != -1 0 0 sum 5 5 number 5 5 2 2 3 3 7 7 Input 5 2 3 5 2 3 10 Print sum  10

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 = false Loop while (!found). if (expression) found = true. End loop Initialization Testing Updating

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.

Solution Start Program randomNumber = …  will be discussed later guessedRight = false loop while (not guessedRight) Read guess if (guess = randomNumber) guessedRight = true Print “You guessed the number correctly !” else if (guess < randomNumber) Print “Your guess is lower than the number” else Print “Your guess is higher than the number” End loop End Program

Solution start randomNumber = … Read guess No end Yes Not guessedRight guessedRight = false guessedRight = true guess = randomNumber Yes No Print “Correct Guess” guess < randomNumber Print “Guess is Lower” Print “Guess is Higher” No Yes

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.

Difference do…while Loop while Loop for Loop

Example SECRET_CODE = 1234 do Print "Type the secret code number to enter." Read code while (code!=SECRET_CODE) Print "Well done, you can now enter" SECRET_CODE = 1234 No Print msg Print input msg Read code Yes code != SECRET_CODE

Nested loop: loop in loop Example: Print the following using loops. * ** *** **** ***** 5 rows : Row 1  1 star Row 2  2 stars … Row 5  5 stars  We need a loop for the rows  We need loops for columns  The number of stars in a row is equal to the row#  Need nested loop  Since the # of iterations are known  for loops

Nested loop: loop in loop Solution: For (i = 1 to 5, step 1) For (j = 1 to i, step 1) print(" *") End For move cursor to next line End For Output: * ** *** **** *****

Chapter Summary Looping mechanisms: ▫Counter-controlled while loop  for loop ▫Sentinel-controlled while loop ▫Flag-controlled while loop ▫ do … while loop Nested control structures

Download ppt "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."

Similar presentations