Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JAVA PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM DESIGN, 3E Control Structures II: Repetition CHAPTER 5 Java Programming: From Problem Analysis to Program Design, 3e 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 2 Java Programming: From Problem Analysis to Program Design, 3e 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 3 Java Programming: From Problem Analysis to Program Design, 3e 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 4 Java Programming: From Problem Analysis to Program Design, 3e THE WHILE LOOPING (REPETITION) STRUCTURE (CONTINUED) 5 Java Programming: From Problem Analysis to Program Design, 3e THE WHILE LOOPING (REPETITION) STRUCTURE (CONTINUED) Example 5-1 i = 0; while (i <= 20) { System.out.print(i + " "); i = i + 5; } System.out.println(); //Line 1 //Line 2 //Line 3 //Line 4 //Line 5 Output: 0 5 10 15 20 6 Java Programming: From Problem Analysis to Program Design, 3e THE WHILE LOOPING (REPETITION) STRUCTURE (CONTINUED) Typically, while loops are written in the following form: 7 Java Programming: From Problem Analysis to Program Design, 3e COUNTER-CONTROLLED WHILE LOOP Used when exact number of data or entry pieces is known General form: 8 Java Programming: From Problem Analysis to Program Design, 3e SENTINEL-CONTROLLED WHILE LOOP Used when exact number of entry pieces is unknown but last entry (special/sentinel value) is known General form: 9 Java Programming: From Problem Analysis to Program Design, 3e FLAG-CONTROLLED WHILE LOOP Boolean value used to control loop General form: 10 Java Programming: From Problem Analysis to Program Design, 3e 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 11 EOF(END OF FILE)-CONTROLLED WHILE LOOP (CONTINUED) Java Programming: From Problem Analysis to Program Design, 3e 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: 12 Java Programming: From Problem Analysis to Program Design, 3e EOF(END OF FILE)-CONTROLLED WHILE LOOP (CONTINUED) Suppose that inFile is a Scanner object initialized to the input file; in this case, the EOFcontrolled while loop takes the following form: 13 Java Programming: From Problem Analysis to Program Design, 3e PROGRAMMING EXAMPLE: CHECKING ACCOUNT BALANCE Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount Output: account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals 14 Java Programming: From Problem Analysis to Program Design, 3e PROGRAMMING EXAMPLE: CHECKING ACCOUNT BALANCE (CONTINUED) Solution Read data EOF-controlled loop switch structure of transaction types Determine action (add to balance or subtract from balance depending on transaction type) 15 Java Programming: From Problem Analysis to Program Design, 3e 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) int previous1 = Fibonacci number 1 int previous2 = Fibonacci number 2 int nthFibonacci = position of nth Fibonacci number Output: nth Fibonacci number 16 PROGRAMMING EXAMPLE: FIBONACCI NUMBER (SOLUTION) Java Programming: From Problem Analysis to Program Design, 3e 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 17 Java Programming: From Problem Analysis to Program Design, 3e 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 18 Java Programming: From Problem Analysis to Program Design, 3e THE FOR LOOPING (REPETITION) STRUCTURE (CONTINUED) Execution Initial statement executes The loop condition evaluated If loop condition evaluates to true, execute for loop statement and execute update statement Repeat until loop condition is false 19 Java Programming: From Problem Analysis to Program Design, 3e THE FOR LOOPING (REPETITION) STRUCTURE (CONTINUED) 20 Java Programming: From Problem Analysis to Program Design, 3e THE FOR LOOPING (REPETITION) STRUCTURE (CONTINUED) Example 5-8 The following for loop prints the first 10 nonnegative integers: for (i = 0; i < 10; i++) System.out.print(i + " "); System.out.println(); 21 THE FOR LOOPING (REPETITION) STRUCTURE (CONTINUED) Java Programming: From Problem Analysis to Program Design, 3e 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("*"); } 2. for (i = 1; i <= 5; i++) System.out.println("Hello"); System.out.println("*"); This loop outputs the word Hello five times and the star only once 22 Java Programming: From Problem Analysis to Program Design, 3e 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 23 Java Programming: From Problem Analysis to Program Design, 3e THE FOR LOOPING (REPETITION) STRUCTURE (CONTINUED) If logical expression is omitted, it is assumed to be true for statement ending in semicolon is empty 24 Java Programming: From Problem Analysis to Program Design, 3e 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 25 PROGRAMMING EXAMPLE: CLASSIFY NUMBERS (SOLUTION) Java Programming: From Problem Analysis to Program Design, 3e 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 26 Java Programming: From Problem Analysis to Program Design, 3e THE DO…WHILE LOOP (REPETITION) STRUCTURE Syntax: Statements executed first, then logical expression evaluated Statement(s) executed at least once then continued if logical expression is true 27 Java Programming: From Problem Analysis to Program Design, 3e DO…WHILE LOOP (POST-TEST LOOP) 28 Java Programming: From Problem Analysis to Program Design, 3e 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 29 Java Programming: From Problem Analysis to Program Design, 3e 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 30 Java Programming: From Problem Analysis to Program Design, 3e 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 31 Java Programming: From Problem Analysis to Program Design, 3e 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: * ** *** **** ***** 32 Java Programming: From Problem Analysis to Program Design, 3e 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 33