1 / 33

Repetition-Counter control Loop

Chapter 4: Control Structures. Repetition-Counter control Loop. 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?.

sibyl
Télécharger la présentation

Repetition-Counter control Loop

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4: Control Structures Repetition-Counter control Loop

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

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

  4. Why Is Repetition Needed? 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?

  5. Why Is Repetition Needed? The Algorithm • Create a variable to hold the sum. • Initialize the sum to zero. • Create a variable to hold a counter from 1 to 100. • Initialize the counter to 1. • While the counter is less-than-or-equal to 100 • add the counter to the sum • add one to the counter • Now repeat • Print the sum

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

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

  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.

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

  10. While Loop Types • Counter-Controlled Loop • Sentinel-Controlled Loop • Flag-Controlled Loop

  11. 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 = … or Read N (1) Initialization stmt. counter = 0 (2) Loop condition counter < N No Yes do operation counter = counter + 1 (3) Update stmt.

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

  13. start Read setSize counter = 0 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 sum = 0 counter < setSize No number setSize counter sum Yes 3 0 1 0 Read number Output 1 10 1 sum = sum + number 3 1 10 4 15 11 4 2 counter = counter + 1 3 15 Print sum end

  14. The while Looping (Repetition) Structure • Syntax: while (expression) statement • Statements must change value of expression to false. • A loop that continues to execute endlessly is called an infinite loop (expression is always true).

  15. The while Looping (Repetition) Structure Example 5-1 i = 0; while (i <= 20) { System.out.print(i + " "); i = i + 5; } System.out.println(); Output 0 5 10 15 20

  16. The while Looping (Repetition) Structure Typically, while loops are written in the following form: //initialize the loop control variable(s) while (expression) //expression tests the LCV { . . . //update the loop control variable(s) . . }

  17. Counter-Controlled while Loop • Used when exact number of data or entry pieces is known. • General form: int N = //value input by user or specified //in program int counter = 0; while (counter < N) { . . . counter++; . . }

  18. Counter-Controlled while Loop-Example 5-3 //Counter-controlled while loopimport java.util.*;publicclass CounterControlledWhileLoop{static Scanner console = new Scanner(System.in);publicstaticvoid main(String[] args) {int limit; //store the number of items//in the listint number; //variable to store the numberint sum; //variable to store the sumint counter; //loop control variable System.out.print("Enter the number of " + "integers in the list: "); limit = console.nextInt(); System.out.println(); sum = 0; counter = 0; System.out.println("Enter " + limit+ " integers.");

  19. Counter-Controlled while Loop-Example 5-3 (continued) while (counter < limit) { number = console.nextInt(); sum = sum + number; counter++; } System.out.printf("The sum of the %d " +"numbers = %d%n", limit, sum); if (counter != 0) System.out.printf("The average = %d%n",(sum / counter)); else System.out.println("No input."); } } Sample Run: Enter the number of integers I the list: 4 Enter 4 Integers 2 1 5 8 The sum of the 4 numbers = 16 The average = 4

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

  21. Counter-Controlled Loop –For Loop The for loop does not have a standard flowcharting method and you will find it done in different ways. N = … or Read N N = … or Read N Can be simplified to: counter = 1 For counter = 1 to N, step 1 counter <= N No do operation Yes do operation Next counter counter = counter + 1

  22. Example • 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. • 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})

  23. start Solution Read N max = 0 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 (1) For counter = 1 to N, step 1 Yes Read number number > max No Yes max = number Next counter end

  24. start start (2) • Trace the developed algorithm. • Assume N to be 4 and the following set to be the numbers {5 2 6 1} Read N max = 0 5 2 2 For counter = 1 to N, step 1 Yes 6 3 6 Read number number counter max N 5 1 4 4 1 0 number > max No Yes 5 max = number Next counter Print max  6 end

  25. The for Looping (Repetition) Structure • Specialized form of while loop. • Its primary purpose is to simplify the writing of counter-controlled loops. For this reason, the forloop is typically called a counted or indexed for loop. . • Syntax: for (initial statement; loop condition; update statement) statement

  26. The for Looping (Repetition) Structure • Execution: • Initial statement executes. • Loop condition is evaluated. • If loop condition evaluates to true, • execute for loop statement and • execute update statement. • Repeat step 2 until loop condition is false.

  27. The for Looping (Repetition) Structure Example 5-9 The following for loop prints the first 10 nonnegative integers: for (i = 0; i < 10; i++) System.out.print(i + " ");

  28. The for Looping (Repetition) Structure Example 5-10 • The following for loop outputs the word Hello and a star (on separate lines) five times: for (i = 1; i <= 5; i++) { System.out.println("Hello"); System.out.println("*"); } 2. The following for loop outputs the word Hello five times and the star only once: for (i = 1; i <= 5; i++) System.out.println("Hello"); System.out.println("*");

  29. The for Looping (Repetition) Structure • Does not execute if loop condition is initially false. • Update expression changes value of loop control variable, eventually making it false. • If loop condition is always true, result is an infinite loop. • Infinite loop can be specified by omitting all three control statements. • If loop condition is omitted, it is assumed to be true. • Action of for loop ending in semicolon is empty.

  30. For Loop Programming Example: Classify Numbers • Input: Nintegers (positive, negative, and zeros). int N = 20; //N easily modified • Output: Number of 0s, number of even integers, number of odd integers.

  31. For Loop Programming Example: Classify Numbers (solution) for (counter = 1; counter <= N; counter++) { number = console.nextInt(); System.out.print(number + " "); switch (number % 2) { case 0: evens++; if (number == 0) zeros++; break; case 1: case -1: odds++; } //end switch } //end for loop

  32. While Loop Programming Example: Fibonacci Number • Fibonacci formula for any Fibonacci sequence: an = an-1 + an-2 • Input: First two Fibonacci numbers in sequence, position in sequence of desired Fibonacci number (n). • intprevious1 = Fibonacci number 1 • intprevious2 = Fibonacci number 2 • intnthFibonacci = Position of nth Fibonacci number • Output: nth Fibonacci number.

  33. While Loop Programming Example: Fibonacci Number if (nthFibonacci == 1) current = previous1; else if (nthFibonacci == 2) current = previous2; else { counter = 3; while (counter <= nthFibonacci) { current = previous2 + previous1; previous1 = previous2; previous2 = current; counter++; } } • Final result found in last value of current.

More Related