Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

Similar presentations


Presentation on theme: "Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,"— Presentation transcript:

1 Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

2 2 Chapter Objectives  Learn about repetition (looping) control structures.  Explore how to construct and use count- controlled, sentinel-controlled and flag- controlled repetition structures.  Examine break and continue statements.  Discover how to form and use nested control structures.

3 3 How can you solve the following problem:  What is the sum of all the numbers from 1 to 100. Why Is Repetition Needed?  The answer will be 1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100.

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

5 5 This solution has two major problems.  Firstly, it’s tedious and it would take a long time to type in. There is also a high risk of making an error while typing it in.  Secondly, 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?

6 6 Develop the Algorithm 1.Create a variable to hold the sum. 2.Initialise the sum to zero. 3.Create a variable to hold a counter from 1 to 100. 4.Initialise 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 Why Is Repetition Needed?

7 7 We can use pseudo-code notation to make this less vague. sum = 0 count = 1 loop while count <= 100 sum = sum + count count++ endloop print sum THIS IS NOT JAVA! This is only pseudo-code and won’t compile. Why Is Repetition Needed?

8 8 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! Why Is Repetition Needed?

9 9  Now we need to turn our pseudo-code into Java.  Java has 3 repetition structures: while, for and do … while.  One way Java supports repetition is using While statements.  Syntax: while (expression) { // body statements }  The expression MUST be placed inside parentheses.  As with an if statement, the expression part is evaluated to determine whether or not the statements should be executed.  The body of the loop is enclosed in { and }. The while Looping (Repetition) Structure

10 10 1.public class FirstLoop 2.{ 3. public static void main(String[] args) 4. { 5. int sum = 0; 6. int count = 1; 7. while (count <= 100) { 8. sum = sum + count; 9. count++; 10. } 11. System.out.println("Sum = “ + sum); 12. } 13.} The while Looping (Repetition) Structure

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

12 12 The while Looping (Repetition) Structure Example 5-1 i = 0; //Line 1 while (i <= 20) //Line 2 { System.out.print(i + " "); //Line 3 i = i + 5; //Line 4 } System.out.println(); //Line 5 Output 0 5 10 15 20 What is the value of i at the end? What will happen if you omit i= i + 5; ? What will happen if you omit i =0; ? i is called LCV

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

14 14 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++;. }

15 15 import java.util.*; public class Example5_3 { static Scanner console = new Scanner(System.in); public static void main (String[] args) { int limit; //store the number of items //in the list int number; //variable to store the number int sum; //variable to store the sum int counter; //loop control variable System.out.println("Line 1: Enter data for " + "processing"); //Line 1 limit =console.nextInt(); //Line 2 sum = 0; //Line 3 counter = 0; //Line 4 Counter-Controlled while Loop Example5_3

16 16 Example5_3 while(counter < limit) //Line 5 { number = console.nextInt(); //Line 6 sum = sum + number; //Line 7 counter++; //Line 8 } System.out.printf("Line 9: The sum of the %d " + " numbers = %d%n",limit, sum); //Line 9 if(counter != 0) //Line 10 System.out.printf("Line 11: The average = %d%n", (sum / counter)); //Line 11 else //Line 12 System.out.println("Line 13: No input."); //Line 13 } } Counter-Controlled while Loop Line 1: Enter data for processing 12 8 9 2 3 90 38 56 8 23 89 7 2 8 3 8 Line 9: The sum of the 12 numbers = 335 Line 11: The average = 2

17 17 Sentinel-Controlled while Loop  Used when exact number of entry pieces is unknown, but last entry (special/sentinel value) is known.  General form: Input the first data item into variable; while (variable != sentinel) {. input a data item into variable;. }

18 18 import java.util.*; public class Example5_4{ static Scanner console = new Scanner(System.in); static final int SENTINEL = -999; public static void main (String[] args) { int number; int sum = 0; int count = 0; System.out.println("Line 1: Enter positive integers " + "ending with "+ SENTINEL); number = console.nextInt(); while(number != SENTINEL) { sum = sum + number; count++; number = console.nextInt(); } System.out.println("Line 7: The sum of " + count + " numbers = " + sum); if(count != 0) System.out.println("Line 9: The average = " + (sum / count)); else System.out.println("Line 11: No input."); } } Sentinel-Controlled while Loop Example5_4 Line 1: Enter positive integers ending with -999 34 23 9 45 78 0 77 8 3 5 -999 Line 7: The sum of 10 numbers = 282 Line 9: The average = 28

19 19 Flag-Controlled while Loop  Boolean value used to control loop.  General form: boolean found = false; //initialize LCV while (!found) // test LCV {. if (expression) found = true; //update LCV. }

20 20 Input - Controlled while Loop  Sentinel value is not always appropriate, programmer sometimes does not know what sentinel is.  In this situation, we can use the input- controlled while loop structure.  console acts as LCV.  The method hasNext, of the class Scanner, returns true if there is an input in the input stream; otherwise, it returns false.  The expression console.hasNext() acts as the loop condition.  Expressions such as console.nextInt() update the value of the loop condition.

21 21 Input - Controlled while Loop  A general form of the input - controlled while loop that uses the Scanner object console to input data is: while (console.hasNext()) { //Get the next input and store it in an //appropriate variable //Process data }

22 22 import java.util.*; public class Example5_7{ static Scanner console = new Scanner(System.in); public static void main (String[] args) { int num; int sum = 0; System.out.println("Enter numbers then press Ctrl key and press z: "); while(console.hasNext()) { num = console.nextInt(); sum = sum + num; } System.out.printf("Sum = %d%n", sum); } } Input - Controlled while Loop Example5_7 Enter numbers then press Ctrl key and press z: 2 4 5 Sum = 11

23 23 Programming Example: Fibonacci Number  Fibonacci formula for any Fibonacci sequence: a n = a n-1 + a n-2  Input: First two Fibonacci numbers in sequence, position in sequence of desired Fibonacci number (n).  int previous1 = Fibonacci number 1  int previous2 = Fibonacci number 2  int nthFibonacci = Position of nth Fibonacci number  Output: nth Fibonacci number.

24 24 Programming Example: Fibonacci Number (Solution) 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.

25 25 The for Looping (Repetition) Structure  Specialized form of while loop.  Simplifies the writing of count-controlled loops.  Syntax: for (initial statement; loop condition; update statement) statement

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

27 27 The for Looping (Repetition) Structure Example 5-8 The following for loop prints the first 10 positive integers: for (i = 0; i < 10; i++) System.out.print(i + " "); System.out.println(); Output 0 1 2 3 4 5 6 7 8 9

28 28 The for Looping (Repetition) Structure Example 5-9 1.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("*"); } Hello * Hello * Hello * Hello * Hello * Hello * 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 29 Example 5-10 What will the following for loop execute? for ( i = 0; i < 5; ++i); System.out.println(“*”); The for Looping (Repetition) Structure Check examples 5-11, 5-12, 5-13 for nice ideas when using for loop.

30 30 The for Looping (Repetition) Structure  Does not execute if initial condition is 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: for (;;) System.out.println(“Hello”); //infinite loop printing Hello  If loop condition is omitted, it is assumed to be true.  for statement ending in semicolon is empty.

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

32 32 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

33 33 The do…while Loop (Repetition) Structure  Syntax: do statement while (expression);  Statements are executed first and then expression is evaluated.  Statements are executed at least once and then continued if expression is true.

34 34 do…while Loop

35 35  In a while or for loop: condition is evaluated before executing the body of the loop  pre-test loops.  In a do … while loop: condition is evaluated after executing the body of the loop  post-test loop. do…while Loop (Post-Test Loop)

36 36 (a) i = 11; while(i <= 10) { System.out.print(i + " "); i = i + 5; } System.out.println(); do…while Loop (Post-Test Loop) Example 5-16: what does each loop produce? (b) i = 11; do { System.out.print(i + " "); i = i + 5; } while(i <= 10); System.out.println(); 11

37 37 When is do…while loop useful ?? Check example 5-17 to figure out! do…while Loop (Post-Test Loop)

38 38 Note…  All three loops: while, for and do…while have their place in Java. One loop can often replace another.  For example do..while loop can replace while loop as follow: if (expression) do action while(expression);  Replaces: while (expression) action

39 39 break Statements  Used to exit early from a loop.  Used to skip remainder of switch structure.  Can be placed within if statement of a loop.  If condition is met, loop is exited immediately.

40 40 sum = 0; while(console.hasNext()) { num = console.nextInt(); if(num < 0) //if number is negative, terminate the loop { System.out.println("Negative number found in data"); break; } sum= sum + num; } break Statements Example: Find the sum of a set of positive numbers, if the data set contains a negative number stop summing.

41 41 continue Statements  Used in while, for, and do... while structures.  When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop.  When executed in a while / do … while structure, expression is evaluated immediately after continue statement.  In a for structure, the update statement is executed after the continue statement; the loop condition then executes.

42 42 continue Statements Example: Find the sum of a set of positive numbers, if a negative number appears in the data set skip it and read the following number. sum = 0; while(console.hasNext()) { num = console.nextInt(); if(num < 0) //if number is negative, read next number { System.out.println("Negative number found in data"); continue; } sum= sum + num; }

43 43 Nested Control Structures  Provides new power, subtlety, and complexity.  if, if … else, and switch structures can be placed within while loops.  for loops can be found within other for loops.

44 44 Nested Control Structures (Example) for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) System.out.print(" *"); System.out.println(); } Output: * ** *** **** ***** Check the rest of the text book examples!

45 45 Overall guidelines for loops  If you know in advance how many times the loop has to iterate - use a for loop.  Never change the counter variable of a for loop in the loop body - you can get some strange results.  For while and do…while loops, make sure that the variable you are checking in the condition is the same variable that you are changing in the loop body.  Finally, be aware of infinite loops!

46 46 Chapter Summary  Looping mechanisms:  Counter-controlled while loop  Sentinel-controlled while loop  Flag-controlled while loop  for loop  do … while loop  break statements  continue statements  Nested control structures


Download ppt "Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,"

Similar presentations


Ads by Google