## Slide #1.

presentation slides for JAVA, JAVA, JAVA Object-Oriented Problem Solving Third Edition Ralph Morelli | Ralph Walde Trinity College Hartford, CT published by Prentice Hall
More slides like this

## Slide #2.

Java, Java, Java Object Oriented Problem Solving Chapter 6: Control Structures
More slides like this

## Slide #3.

Objectives • Be able to solve problems involving repetition. • Understand the difference among various loop structures. • Know the principles used to design effective loops. • Improve your algorithm design skills. • Understand the goals and principles of structured programming. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #4.

Outline • • • • • • Flow of Control: Repetition Structures Counting Loops Example: Car Loan Graphics Example: Drawing a Checkerboard Conditional Loops Examples: Computing Averages and Data Validation • Principles of Loop Design • The switch Multiway Selection Structure • Object-Oriented Design: Structured Programming Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #5.

Flow-of-Control: Repetition Structures • Repetition structure: a control structure that repeats a statement or a sequence of statements. • Many programming tasks require a repetition structure. • If number of iterations is known, use a counting loop: – Counting the number of times the letter ‘a’ occurs in a document: initialize totalAs to 0 for each character in the document if the character is an 'a' add 1 to totalAs return totalAs as the result – Printing the numbers between 1 and 5000 on invitation cards: for each number, N, from 1 to 5000 print N on the invitation card Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #6.

Flow-of-Control: Repetition Structures • If number of iterations is unknown, we can use a conditional loop. – Searching through the file for a student’s record: repeat the following steps read a record from the file until Erika Wilson's record is read compute Erika Wilson's GPA return gpa as the result – Computing the average monthly bear sightings: initialize sumOfBears and numOfMonths to 0 repeat the following steps read a number from the keyboard add it to the sumOfBears add 1 to numOfMonths until the user wants to stop divide sumOfBears by numOfMonths giving average Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #7.

Counting Loops • The for statement is used for counting loops. for (int k = 0; k < 100; k++) System.out.println("Hello"); // For 100 times // Print "Hello" • Zero-indexing: the loop counter or loop variable k, iterates between 0 and 99. • For statement syntax: for ( initializer ; loop entry condition ; updater ) for loop body ; Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #8.

The For Structure • Syntax: for ( k = 0 ; k < 100 ; k++ ) System.out.println(“Hello”); • Semantics: Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #9.

Loop Variable Scope • If k is declared within the for statement, it cannot be used after the for statement: for (int k = 0; k < 100; k++) System.out.println("Hello"); System.out.println("k = " + k); // Syntax error, k is undeclared • If k is declared before the for statement, it can be used after the for statement: int k = 0; // Declare the loop variable here for (k = 0; k < 100; k++) System.out.println("Hello"); System.out.println("k = " + k); // So it can be used here Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #10.

Loop Bounds • A counting loop starts at an initial value and counts 0 or more iterations until its loop bound is reached. • The loop entry condition tests whether the loop bound has been reached. public void countdown() { for (int k = 10; k > 0; k--) System.out.print(k + " "); System.out.println("BLASTOFF"); } // countdown() • The updater must make progress toward the bound. • Infinite loop: A loops that fails to reach its bound. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #11.

Infinite Loops • Infinite loop examples: for (int k = 0; k < 100 ; k--) System.out.println("Hello"); // k goes 0, -1, -2, ... for (int k = 1; k != 100 ; k+=2) System.out.println("Hello"); // k goes 1,3,…,99,101,... for (int k = 98; k < 100 ; k = k / 2) // k goes 98,49,24, …, 0,0,0 System.out.println("Hello"); • In each case the updater fails to make progress toward the bound and the loop entry condition never becomes false. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #12.

Loop Indentation • Indentation improves readability. • The loop’s meaning is determined by its syntax. • Equivalent loops: for (int k = 10 ; k > 0 ; k--) System.out.print (k + " "); System.out.println( "BLASTOFF" ); // Loop heading // Indent the body // After the loop for (int k = 10 ; k > 0 ; k--) System.out.print (k + " "); System.out.println("BLASTOFF"); for (int k = 10 ; k > 0 ; k--) System.out.print(k + " "); System.out.println("BLASTOFF"); for (int k = 10 ; k > 0 ; k--) System.out.print (k + " "); System.out.println("BLASTOFF"); Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #13.

Compound Loop Body • Compound statement or block :a sequence of statements enclosed within braces, {...}. • For loop body: Can be a simple or compound statement. for (int k = 0; k < 100; k++) // Print 0 5 10 15 ... 95 if (k % 5 == 0) // Loop body is a single if statement System.out.println("k= " + k); for (char k = 'a' ; k <= 'z'; k++) System.out.print (k + " "); for (int k = 1 ; k <= 10; k++) { // Print 'a' 'b' 'c' ... 'z' // Loop body is a single print() // Print 5 10 15 20 ... 50 int m = k * 5; System.out.print (m + " "); // Begin body } Compound statement. // End body for (int k = 1 ; k <= 10; k++) int m = k * 5; System.out.print (m + " "); // Loop body // Syntax error: Outside scope of loop Debugging Tip: Don’t forget the braces! Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #14.

Nested Loops • Suppose you wanted to print the following table: 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 5 10 15 20 6 12 18 24 7 14 21 28 8 16 24 32 9 18 27 36 • You could use a nested for loop. The outer loop prints the four rows and in each row, the inner loop prints the 9 columns. for (int row = 1; row <= 4; row++) { // For each of 4 rows for (int col = 1; col <= 9; col++) // For each of 9 columns System.out.print(col * row + "\t"); // Print 36 numbers System.out.println(); // Start a new row } // for row Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #15.

Nested Loops (cont.) • The table shows the relationship between the row and column variables needed to print the following triangular pattern: # # # # # # # # # # # # # # # Row Column Bound Number of (6 – Row) Symbols 1 6-1 5 2 6-2 4 3 6-3 3 4 6-4 2 5 6-5 1 • You could use the following nested for loop. for (int row = 1; row <= 5; row++) { // For each row for (int col = 1; col <= 6 - row; col++) // Print the row System.out.print('#'); System.out.println(); // And a new row } // for row Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #16.

Example: Car Loan Table • Design a program to print a table for the total cost of car financing options. Loan Rates Years Year Year Year Year Year Year Year 2 3 4 5 6 7 8 8% \$23,469.81 \$25,424.31 \$27,541.59 \$29,835.19 \$32,319.79 \$35,011.30 \$37,926.96 9% \$23,943.82 \$26,198.42 \$28,665.32 \$31,364.50 \$34,317.85 \$37,549.30 \$41,085.02 10% \$24,427.39 \$26,996.07 \$29,834.86 \$32,972.17 \$36,439.38 \$40,271.19 \$44,505.94 11% \$24,920.71 \$27,817.98 \$31,052.09 \$34,662.19 \$38,692.00 \$43,190.31 \$48,211.60 • Nested loop algorithm: Outer loop iterates over the years 2 through 8. The inner loop iterates over the rates 8 through 11. • Cost Formula: a = p(1 +r)n where total cots is a, for a loan of p at a rate of r for a period of n years. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #17.

Implementation: CarLoan Class formats the output. NumberFormat import java.text.NumberFormat; public class CarLoan { public static void main(String args[]) { double carPrice = 20000; // Car's actual price double carPriceWithLoan; // Cost of the car plus financing NumberFormat dollars = NumberFormat.getCurrencyInstance(); NumberFormat percent = NumberFormat.getPercentInstance(); percent.setMaximumFractionDigits(2); // Print table for (int rate = 8; rate <= 11; rate++) // Print column heading System.out.print("\t" + percent.format(rate/100.0) + "\t" ); System.out.println(); for (int years = 2; years <= 8; years++) { // For years 2..8 System.out.print("Year " + years + "\t"); // Print row heading for (int rate = 8; rate <= 11; rate++) { // Calc and print value carPriceWithLoan = carPrice * Math.pow(1 + rate / 100.0 / 365.0, years * 365.0); System.out.print(dollars.format(carPriceWithLoan) + "\t"); } // for rate System.out.println(); // Start a new row } // for years } // main() } // CarLoan Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #18.

Checkerboard Example (Graphics) • A class to draw a checkerboard and checkers. • We use an applet as the GUI and the CheckerBoard class as the computational object. Class constants. import java.awt.*; import java.applet.*; import javax.swing.*; public class CheckerBoardApplet extends JApplet { private CheckerBoard theBoard; public void init() { theBoard = new CheckerBoard(); } public void paint(Graphics g) { theBoard.draw(g); } // paint() } // CheckerBoardApplet Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #19.

CheckerBoard Implementation • Calculating the locations of the checkerboard squares. • Note the use of class constants • Click here for Demo of Checkboard • CheckerBoard.java • CheckerBoardApplet.java Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #20.

Conditional Loops • 3N + 1 problem: If N is any positive integer, then the sequence generated by the following rules will always terminate at 1: Case N is odd N is even • Non-counting algorithm: Algorithm for computing the 3N+1 sequence While N is not equal to 1, do: { Print N. If N is even, divide it by 2, otherwise multiply N by 3 and add 1. } Print N Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Operation N=3*N+1 N=N/2 The loop iterates as long as N != 1 Sentinel bound. The loop terminates when N equals the sentinel value 1. Chapter 6: Control Structures
More slides like this

## Slide #21.

The While Structure • While structure to solve the 3N+1 problem: Initializer Loop body N = 50; while (N != 1) { // System.out.print(N + " "); if (N % 2 == 0) // N = N / 2; // else // N = 3 * N + 1; // } System.out.println(N); // Loop entry condition While N not 1 // Print N If N is even divide it by 2 Updaters If N is odd multiply N by 3 and add 1 Print N • Java’s while statement: while ( loop entry condition ) loop body ; Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Unlike the for statement, the while statement has no builtin initializer and updater. Chapter 6: Control Structures
More slides like this

## Slide #22.

Principles of the While Structure • Effective Design: Loop structure. A loop structure must include an initializer, a boundary condition, and an updater. The updater should guarantee that the boundary condition is reached, so the loop will eventually terminate. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #23.

The Do-While Structure • Problem: How many days will it take for half the lawn to disappear if it loses 2% of its grass a day? Initializer Loop body public int losingGrass(double perCentGrass) { double amtGrass = 100.0; // Initialize amount of grass int nDays = 0; // Initialize day counter do { // Repeat amtGrass -= amtGrass * LOSSRATE; // Update grass ++nDays; // Increment days } while (amtGrass > perCentGrass); // While 50% grass return nDays / 7; // Return number of weeks } // losingGrass() Updater Limit bound: Terminate when a limit is reached. • Java’s do-while statement : No built-in initializer or updater. do loop body while ( loop entry condition ) ; Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #24.

Principles of the Do-While Structure • Effective Design: Do-While Structure. • The do-while loop is designed for solving problems in which at least one iteration must occur. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #25.

More slides like this

## Slide #26.

More slides like this

## Slide #27.

Design Issues • Effective Design: Modularity. Encapsulating code in a method helps reduce redundancy and makes it easier to debug and modify. • Effective Design: Method Decomposition. Methods should have a clear focus. Methods that are too long should be divided into separate methods. • Effective Design: User Interface. Use prompts to inform the user why you are asking for input and what you are asking for. It's also a good idea to confirm that the program has received the correct input. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #28.

More slides like this

## Slide #29.

Main Program for Computing the Average import java.io.*; Object for reading keyboard input. public class Validate { private KeyboardReader input = new KeyboardReader(); // Stuff missing here public static void main( String argv[] ) { System.out.println("This program calculates average grade."); // Prompt Validate avg = new Validate(); double average = avg.inputAndAverageGrades(); if (average == 0) // Error case System.out.println("You didn't enter any grades."); else System.out.println("Your average is " + average ); } // main() } // Validate A basic inputprocess-output algorithm. • SourceCode/Demo: Validate.java • I/O Object: KeyboardReader.java Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #30.

Principles of Loop Design • A counting loop can be used if you know in advance how many iterations are needed. The for statement is used for counting loops. • A while structure should be used if the loop body may be skipped entirely. The while statement is used. • A do-while structure should be used only if a loop requires one or more iterations. The do-whilestatement should be used. • The loop variable, which is used to specify the loop entry condition, must be initialized to an appropriate value and updated on each iteration. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #31.

Principles of Loop Design • A loop's bound, which may be a count, a sentinel, or, more generally, a conditional bound, must be correctly specified in the loop-entry expression, and progress toward it must be made in the updater. • An infinite loop may result if either the initializer, loop-entry expression, or updater expression is not correctly specified. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #32.

The Switch/Break Structure • Multiway selection can also be done with the switch/break structure. switch ( integralExpression ) { case integralValue2 : statement1; break; case integralValue2 : statement2; break; … case integrealValueN : statementN; break; default: statementDefault; } Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #33.

Switch/Break Examples Correct: Prints m=2 int m = 2; switch (m) { case 1 : System.out.println(“m=1”); break; case 2 : System.out.println(“m=2”); break; case 3 : System.out.println(“m=3”); break; default: System.out.println(“default”);} Error: Prints ch=b.ch=c, default char ch = ‘b’; switch (ch) { case ‘a’ : System.out.println(“ch=a”); case ‘b’ : System.out.println(“ch=b”); case ‘c’ : System.out.println(“ch=c”); default: System.out.println(“default”); } Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #34.

Structured Programming • Structured programming: uses a small set of predefined control structures. – Sequence --- The statements in a program are executed in sequential order unless their flow is interrupted by one of the following control structures. – Selection--- The if, if/else, and switch statements are branching statements that allow choice by forking of the control path into two or more alternatives. – Repetition --- The for, while, and do-while statements are looping statements that allow the program to repeat a sequence of statements. – Method Call --- Invoking a method transfers control temporarily to a named method. Control returns to the point of invocation when the method is completed. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #35.

Structured Programming Constructs • No matter how large or small a program is, its flow of control can be built as a combination of these four structures. • Note that each structure has one entry and one exit. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #36.

Debugging: Structured vs. Unstructured Code Unstructured Code uses goto Statement k = 0; System.out.println("k= " + k); goto label1; label2: System.out.println("k= " + k); Problem: If k does not equal 1 on line 4, how would you find the bug? // 1. Unstructured code // 2. k should equal 0 here // 3. // 4. k should equal 1 here With a goto statement, there’s no guarantee control will return to line 4. With a method call, control must return to line 4. Structured Code uses a method call k = 0; System.out.println("k= " + k); someMethod(); System.out.println("k= " + k); Java, Java, Java, 3E by R. Morelli | R. Walde // 1. Unstructured code // 2. k should equal 0 here // 3. // 4. k should equal 1 here Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #37.

Preconditions and Postconditions • A precondition is a condition that must be true before some segment of code is executed. • A postcondition is a condition that must be true after some segment of code is executed. • Example: Pre- and postconditions for an assignment: int k = 0; k = 5; // Precondition: k == 0 // Assignment to k // Postcondition: k == 5 • Example: Pre- and postconditions for a loop: int k = 0; // Precondition: k == 0 while (k < 100) { // While loop k = 2 * k + 2; } // Postcondition: k >= 100 Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #38.

Defensive Programming /** * factorial(n) -- factorial(n) is 1 if n is 0 * factorial(n) is n * n-1 * n-2 * ... * 1 if n > 0 * Precondition: n >= 0 * Postcondition: factorial(n) = 1 if n = 0 * = n * n-1 * n-2 * ... * 1 if n > 0 */ public int factorial(int n) { if (n < 0) { System.out.println(“Error in factorial():, n = “ + n); System.exit(0); } if (n == 0) return 1; else { int f = 1; // Init a temporary variable for (int k = n; k >= 1; k--) // For n down to 1 f = f * k; // Accumulate the product return f; // Return the factorial } } // factorial() Defensive Programming: If the precondition fails, report the error. If precondition is OK, compute the factorial. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #39.

Using Preconditions and Postconditions • Design stage: Using pre- and postconditions helps clarify the design and provides a precise measure of correctness. • Implementation and testing stage: Test data can be designed to demonstrate that the preconditions and postconditions hold for any method or code segment. • Documentation stage: Using pre- and postconditions to document the program makes the program more readable and easier to modify and maintain. • Debugging stage: Using the pre- and postconditions provides precise criteria that can be used to isolate and locate bugs. A method is incorrect if its precondition is true and its postcondition is false. A method is improperly invoked if its precondition is false. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #40.

Design/Programming Tips • Preconditions and postconditions are an effective way of analyzing the logic of your program's loops and methods. They should be identified during the design phase and used throughout development, testing and debugging , and included in the program's documentation. • Develop your program's documentation at the same time that you develop its code. • Acquire and use standard programming techniques for standard programming problems. For example, using a temporary variable to swap the values of two variables is an example of a standard technique. • Use methods wherever appropriate in your own code to encapsulate important sections of code and thereby reduce complexity. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this

## Slide #41.

Technical Terms conditional loop for statement limit bound loop-entry condition pre-condition switch/break structure while statement counting loop infinite loop loop body nested loop repitition structure unit indexing zero indexing Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. do-while statement initializer loop bound postcondition sentinel bound updater Chapter 6: Control Structures
More slides like this

## Slide #42.

Summary Of Important Points • A repetition structure is a control structure that allows a statement or sequence of statements to be repeated. • All loop structures involve three elements -- an initializer, a loop entry condition or a loop boundary condition, and an updater. • Structured programming is the practice of writing programs that are built up from a small set of predefined control structures -- sequence, selection, repetition and method-call. An important feature of these structures is that each has a single entry and exit. • A precondition is a condition that must be true before a certain code segment executes. A postcondition is a condition that must be true when a certain code segment is finished. Preconditions and postconditions should be used in the design, coding, documentation, and debugging of algorithms and methods. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 6: Control Structures
More slides like this