Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition
Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures Java Programming: From Problem Analysis to Program Design, 4e
Why Is Repetition Needed? There are many situations in which the same statements need to be executed several times Example Formulas used to find average grades for students in a class Java Programming: From Problem Analysis to Program Design, 4e
The  while  Looping (Repetition) Structure Syntax while  (expression)   statement Expression is always true in an infinite loop Statements must change value of expression to false  Java Programming: From Problem Analysis to Program Design, 4e
The  while  Looping (Repetition) Structure (continued) Java Programming: From Problem Analysis to Program Design, 4e
The  while  Looping (Repetition) Structure (continued) Example 5-1 i = 0;  //Line 1 while  (i <= 20)  //Line 2 { System.out.print(i + &quot; &quot;);  //Line 3 i = i + 5;  //Line 4 } System.out.println();  //Line 5 Output:  0 5 10 15 20 Java Programming: From Problem Analysis to Program Design, 4e
The  while  Looping (Repetition) Structure (continued) Typically,  while  loops are written in the following form: Java Programming: From Problem Analysis to Program Design, 4e
Counter-Controlled  while  Loop Used when exact number of data or entry pieces is known General form: Java Programming: From Problem Analysis to Program Design, 4e
Sentinel-Controlled  while  Loop Used when exact number of entry pieces is unknown but last entry (special/sentinel value) is known General form: Java Programming: From Problem Analysis to Program Design, 4e
Flag-Controlled  while  Loop Boolean value used to control loop General form: Java Programming: From Problem Analysis to Program Design, 4e
EOF (End of File)-Controlled  while  Loop Used when input is from files Sentinel value is not always appropriate In an EOF-controlled  while  loop that uses the  Scanner  object  console  to input data,  console  acts at the loop control variable The method  hasNext , of the  class   Scanner , returns  true  if there is an input in the input stream; otherwise it returns  false Java Programming: From Problem Analysis to Program Design, 4e
EOF (End of File)-Controlled  while  Loop (continued) The expression  console.hasNext()  evaluates to  true  if there is an input in the input stream; otherwise it returns  false   Expressions such as  console.nextInt()  act as the loop condition A general form of the EOF-controlled  while  loop that uses the  Scanner  object  console  to input data is of the form:  Java Programming: From Problem Analysis to Program Design, 4e
EOF (End of File)-Controlled  while  Loop (continued) Suppose that  inFile  is a  Scanner  object initialized to the input file; in this case, the EOF-controlled  while  loop takes the following form: Java Programming: From Problem Analysis to Program Design, 4e
Java Programming: From Problem Analysis to Program Design, 4e
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  Java Programming: From Problem Analysis to Program Design, 4e
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 Java Programming: From Problem Analysis to Program Design, 4e
The  for  Looping (Repetition) Structure Specialized form of  while  loop Simplifies the writing of count-controlled loops Syntax for  (initial expression; logical expression;  update expression) statement Java Programming: From Problem Analysis to Program Design, 4e
The  for  Looping (Repetition) Structure (continued) Execution Initial statement executes   The loop condition is evaluated If loop condition evaluates to true, execute  for  loop statement  and execute  update statement Repeat until loop condition is  false   Java Programming: From Problem Analysis to Program Design, 4e
The  for  Looping (Repetition) Structure (continued) Java Programming: From Problem Analysis to Program Design, 4e
The  for  Looping (Repetition) Structure (continued) Example 5-9 The following for loop prints the first 10 nonnegative integers: for  (i = 0; i < 10; i++) System.out.print(i + &quot; &quot;); System.out.println(); Java Programming: From Problem Analysis to Program Design, 4e
The  for  Looping (Repetition) Structure (continued) 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(&quot;Hello&quot;);   System.out.println(&quot;*&quot;); } 2.   for  (i = 1; i <= 5; i++) System.out.println(&quot;Hello&quot;); System.out.println(&quot;*&quot;); This loop outputs the word  Hello  five times and the star only once Java Programming: From Problem Analysis to Program Design, 4e
The  for  Looping (Repetition) Structure (continued) Does not execute if initial condition is  false Update expression changes value of loop control variable, eventually making it  false If logical expression is always  true , result is an infinite loop   Infinite loop can be specified by omitting all three control statements   Java Programming: From Problem Analysis to Program Design, 4e
The  for  Looping (Repetition) Structure (continued) If logical expression is omitted, it is assumed to be  true for  statement ending in semicolon is empty Java Programming: From Problem Analysis to Program Design, 4e
Java Programming: From Problem Analysis to Program Design, 4e
Programming Example: Classify Numbers Input:  N   integers (positive, negative, and zeros)  int  N = 20;  //N easily modified Output: number of  0 s, number of even integers, number of odd integers Java Programming: From Problem Analysis to Program Design, 4e
Programming Example: Classify Numbers (Solution) for  (counter = 1; counter <= N; counter++) { number = console.nextInt();  System.out.print(number + &quot; &quot;);  switch  (number % 2) { case  0:  evens++; if  (number == 0) zeros++; break ; case  1: case  -1:  odds++; }  //end switch }  //end for loop Java Programming: From Problem Analysis to Program Design, 4e
Programming Example: Classify Numbers (Solution) (continued) The  switch  statement in Step 3c can also be written as an  if ... else  statement as follows: Java Programming: From Problem Analysis to Program Design, 4e
The  do…while  Loop (Repetition) Structure Syntax Statements executed first, and then  logical   expression  evaluated Statement(s) executed at least once and then continued if  logical   expression  is true Java Programming: From Problem Analysis to Program Design, 4e
do…while  Loop (Post-test Loop) Java Programming: From Problem Analysis to Program Design, 4e
do…while  Loop (Post-test Loop) Java Programming: From Problem Analysis to Program Design, 4e
Java Programming: From Problem Analysis to Program Design, 4e Choosing the Right Looping Structure All three loops have a place in Java If you know or the program can determine in advance the number of repetitions needed, the for loop is the correct choice If you do not know and the program cannot determine in advance the number of repetitions needed, and it could be zero, the while loop is the right choice If you do not know and the program cannot determine in advance the number of repetitions needed, and it is at least one, the do...while loop is the right choice
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 exited immediately   Java Programming: From Problem Analysis to Program Design, 4e
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 evaluated immediately after  continue  statement  In a  for  structure, the update expression is executed after the  continue  statement; then the loop condition executes  Java Programming: From Problem Analysis to Program Design, 4e
Nested Control Structure 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  Java Programming: From Problem Analysis to Program Design, 4e
Nested Control Structure (Example) for  (i = 1; i <= 5; i++) { for  (j = 1; j <= i; j++)   System.out.print( &quot;   * &quot; ); System.out.println(); } Output : * ** *** **** ***** Java Programming: From Problem Analysis to Program Design, 4e
Chapter Summary Looping Mechanisms Counter-controlled  while  loop Sentinel-controlled  while  loop Flag-controlled  while  loop EOF-controlled  while  loop for  loop do … while  loop break  statements continue  statements Nested control structures Java Programming: From Problem Analysis to Program Design, 4e

9781439035665 ppt ch05

  • 1.
    Java Programming: FromProblem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition
  • 2.
    Chapter Objectives Learnabout repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures Java Programming: From Problem Analysis to Program Design, 4e
  • 3.
    Why Is RepetitionNeeded? There are many situations in which the same statements need to be executed several times Example Formulas used to find average grades for students in a class Java Programming: From Problem Analysis to Program Design, 4e
  • 4.
    The while Looping (Repetition) Structure Syntax while (expression) statement Expression is always true in an infinite loop Statements must change value of expression to false Java Programming: From Problem Analysis to Program Design, 4e
  • 5.
    The while Looping (Repetition) Structure (continued) Java Programming: From Problem Analysis to Program Design, 4e
  • 6.
    The while Looping (Repetition) Structure (continued) Example 5-1 i = 0; //Line 1 while (i <= 20) //Line 2 { System.out.print(i + &quot; &quot;); //Line 3 i = i + 5; //Line 4 } System.out.println(); //Line 5 Output: 0 5 10 15 20 Java Programming: From Problem Analysis to Program Design, 4e
  • 7.
    The while Looping (Repetition) Structure (continued) Typically, while loops are written in the following form: Java Programming: From Problem Analysis to Program Design, 4e
  • 8.
    Counter-Controlled while Loop Used when exact number of data or entry pieces is known General form: Java Programming: From Problem Analysis to Program Design, 4e
  • 9.
    Sentinel-Controlled while Loop Used when exact number of entry pieces is unknown but last entry (special/sentinel value) is known General form: Java Programming: From Problem Analysis to Program Design, 4e
  • 10.
    Flag-Controlled while Loop Boolean value used to control loop General form: Java Programming: From Problem Analysis to Program Design, 4e
  • 11.
    EOF (End ofFile)-Controlled while Loop Used when input is from files Sentinel value is not always appropriate In an EOF-controlled while loop that uses the Scanner object console to input data, console acts at the loop control variable The method hasNext , of the class Scanner , returns true if there is an input in the input stream; otherwise it returns false Java Programming: From Problem Analysis to Program Design, 4e
  • 12.
    EOF (End ofFile)-Controlled while Loop (continued) The expression console.hasNext() evaluates to true if there is an input in the input stream; otherwise it returns false Expressions such as console.nextInt() act as the loop condition A general form of the EOF-controlled while loop that uses the Scanner object console to input data is of the form: Java Programming: From Problem Analysis to Program Design, 4e
  • 13.
    EOF (End ofFile)-Controlled while Loop (continued) Suppose that inFile is a Scanner object initialized to the input file; in this case, the EOF-controlled while loop takes the following form: Java Programming: From Problem Analysis to Program Design, 4e
  • 14.
    Java Programming: FromProblem Analysis to Program Design, 4e
  • 15.
    Programming Example: FibonacciNumber 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 Java Programming: From Problem Analysis to Program Design, 4e
  • 16.
    Programming Example: FibonacciNumber (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 Java Programming: From Problem Analysis to Program Design, 4e
  • 17.
    The for Looping (Repetition) Structure Specialized form of while loop Simplifies the writing of count-controlled loops Syntax for (initial expression; logical expression; update expression) statement Java Programming: From Problem Analysis to Program Design, 4e
  • 18.
    The for Looping (Repetition) Structure (continued) Execution Initial statement executes The loop condition is evaluated If loop condition evaluates to true, execute for loop statement and execute update statement Repeat until loop condition is false Java Programming: From Problem Analysis to Program Design, 4e
  • 19.
    The for Looping (Repetition) Structure (continued) Java Programming: From Problem Analysis to Program Design, 4e
  • 20.
    The for Looping (Repetition) Structure (continued) Example 5-9 The following for loop prints the first 10 nonnegative integers: for (i = 0; i < 10; i++) System.out.print(i + &quot; &quot;); System.out.println(); Java Programming: From Problem Analysis to Program Design, 4e
  • 21.
    The for Looping (Repetition) Structure (continued) 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(&quot;Hello&quot;); System.out.println(&quot;*&quot;); } 2. for (i = 1; i <= 5; i++) System.out.println(&quot;Hello&quot;); System.out.println(&quot;*&quot;); This loop outputs the word Hello five times and the star only once Java Programming: From Problem Analysis to Program Design, 4e
  • 22.
    The for Looping (Repetition) Structure (continued) Does not execute if initial condition is false Update expression changes value of loop control variable, eventually making it false If logical expression is always true , result is an infinite loop Infinite loop can be specified by omitting all three control statements Java Programming: From Problem Analysis to Program Design, 4e
  • 23.
    The for Looping (Repetition) Structure (continued) If logical expression is omitted, it is assumed to be true for statement ending in semicolon is empty Java Programming: From Problem Analysis to Program Design, 4e
  • 24.
    Java Programming: FromProblem Analysis to Program Design, 4e
  • 25.
    Programming Example: ClassifyNumbers Input: N integers (positive, negative, and zeros) int N = 20; //N easily modified Output: number of 0 s, number of even integers, number of odd integers Java Programming: From Problem Analysis to Program Design, 4e
  • 26.
    Programming Example: ClassifyNumbers (Solution) for (counter = 1; counter <= N; counter++) { number = console.nextInt(); System.out.print(number + &quot; &quot;); switch (number % 2) { case 0: evens++; if (number == 0) zeros++; break ; case 1: case -1: odds++; } //end switch } //end for loop Java Programming: From Problem Analysis to Program Design, 4e
  • 27.
    Programming Example: ClassifyNumbers (Solution) (continued) The switch statement in Step 3c can also be written as an if ... else statement as follows: Java Programming: From Problem Analysis to Program Design, 4e
  • 28.
    The do…while Loop (Repetition) Structure Syntax Statements executed first, and then logical expression evaluated Statement(s) executed at least once and then continued if logical expression is true Java Programming: From Problem Analysis to Program Design, 4e
  • 29.
    do…while Loop(Post-test Loop) Java Programming: From Problem Analysis to Program Design, 4e
  • 30.
    do…while Loop(Post-test Loop) Java Programming: From Problem Analysis to Program Design, 4e
  • 31.
    Java Programming: FromProblem Analysis to Program Design, 4e Choosing the Right Looping Structure All three loops have a place in Java If you know or the program can determine in advance the number of repetitions needed, the for loop is the correct choice If you do not know and the program cannot determine in advance the number of repetitions needed, and it could be zero, the while loop is the right choice If you do not know and the program cannot determine in advance the number of repetitions needed, and it is at least one, the do...while loop is the right choice
  • 32.
    break StatementsUsed 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 exited immediately Java Programming: From Problem Analysis to Program Design, 4e
  • 33.
    continue StatementsUsed 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 evaluated immediately after continue statement In a for structure, the update expression is executed after the continue statement; then the loop condition executes Java Programming: From Problem Analysis to Program Design, 4e
  • 34.
    Nested Control StructureProvides 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 Java Programming: From Problem Analysis to Program Design, 4e
  • 35.
    Nested Control Structure(Example) for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) System.out.print( &quot; * &quot; ); System.out.println(); } Output : * ** *** **** ***** Java Programming: From Problem Analysis to Program Design, 4e
  • 36.
    Chapter Summary LoopingMechanisms Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop EOF-controlled while loop for loop do … while loop break statements continue statements Nested control structures Java Programming: From Problem Analysis to Program Design, 4e