Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 01321308071 Chapter 4 Loops.

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.1 Chapter 5 Loops.
Chapter 4 Loops Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X.
Computer Science 1620 Loops.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Loops.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
1 LOOPS. 2 Repetitions while Loops do-while Loops for Loops break and continue.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 5 Control Statements.
Introduction to Java Programming, 4E Y. Daniel Liang.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Chapter 4 Loops Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 3 Control Statements F Selection Statements –Using if and if...else –Nested if Statements –Using switch Statements –Conditional Operator F Repetition.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 4 Loops.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Java Programming: From the Ground Up
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 5 Loops.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 4 Loops Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 5 Loops.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Loops 1. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved while Loop Flow.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Chapter 5 Loops.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
1 Chapter 4 - Control Statements Conditions if Statement && Logical Operator || Logical Operator ! Logical Operator switch Statement while Loop do Loop.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 5 Loops.
Loops George Mason University. Loop Structure Loop- A structure that allows repeated execution of a block of statements Loop body- A block of statements;
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 4 Loops.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
1 Chapter 5 Control Statements. 2 Objectives F To understand the flow of control in selection and loop statements. F To use Boolean expressions to control.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 06 Title: Iterative/Repetitive Control Structures Reference: MalikFarrell, chap 1, Liang Ch 4.
Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 4: Looping Structures LECTURER : MRS ROHANI HASSAN
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 5 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
REPETITION CONTROL STRUCTURE
Chapter 4 – Loops Dr. Larry G. Thomas – University of Toledo / LCCC
Chapter 4 Loops DDC 2133 Programming II.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4 Control structures and Loops
Chapter 5 Control Statements
Chapter 3 Control Statements
Chapter 5 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 5 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 4: Loops and Iteration
Presentation transcript:

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objectives F To write programs for executing statements repeatedly using a while loop (§4.2). F To develop a program for GuessNumber and SubtractionQuizLoop (§4.2.1). F To follow the loop design strategy to develop loops (§4.2.2). F To develop a program for SubtractionQuizLoop (§4.2.3). F To control a loop with a sentinel value (§4.2.3). F To obtain large input from a file using input redirection rather than typing from the keyboard (§4.2.4). F To write loops using do-while statements (§4.3). F To write loops using for statements (§4.4). F To discover the similarities and differences of three types of loop statements (§4.5). F To write nested loops (§4.6). F To learn the techniques for minimizing numerical errors (§4.7). F To learn loops from a variety of examples (GCD, FutureTuition, MonteCarloSimulation) (§4.8). F To implement program control with break and continue (§4.9). F (GUI) To control a loop with a confirmation dialog (§4.10).

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times: System.out.println("Welcome to Java!"); So, how do you solve this problem?

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Java Loops – while, do…While, & for 4  There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.  Java has very flexible three looping mechanisms. You can use one of the following three loops: while Loop do...while Loop for Loop

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Opening Problem System.out.println("Welcome to Java!"); … System.out.println("Welcome to Java!"); Problem: 100 times

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved while Loop pseudocode syntax while Java syntax while ( ) { } Use a loop statement if you need to do the same thing repeatedly. The condition is at the bottom of the loop (in contrast to the while loop, where the condition is at the top of the loop). The compiler requires putting a ";" at the very end, after the do loop's condition. Proper style dictates putting the "while" part on the same line as the " } "

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved while Loop Flow Chart while (loop-continuation-condition) { // loop-body; Statement(s); } // end of while int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; } // end of while

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved while Loop int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; } // end of while A while loop is a control structure that allows you to repeat a task a certain number of times. Using loop statement means tell the computer to print a string a hundred times without coding: public class Welcome { public static void main (String [ ] args){ int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; } // end of while } // end of main method } // end of class

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Here key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Syntax while(Boolean_expression) { //Statements } Example: public class Test1 { public static void main(String args[]){ int x= 10; while( x < 20 ){ System.out.print("value of x :" + x); x++; System.out.print("\n"); } //end of while } // end of main } //end of class

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved while Loop  Write a main method that finds the sum of user- entered integers where is a sentinel value. public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int sum = 0; // sum of user-entered values int x; // a user-entered value System.out.print("Enter an integer ( to quit): "); x = stdIn.nextInt(); while (x != ) { sum = sum + x; System.out.print("Enter an integer ( to quit): "); x = stdIn.nextInt(); } // end of while System.out.println("The sum is " + sum); } // end main

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved import java.util.Scanner; public class SentinelValue { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Read an initial data System.out.print( "Enter an int value (the program exits if the input is 0): "); int data = input.nextInt(); // Keep reading data until the input is 0 int sum = 0; while (data != 0) { sum += data; // Read the next data System.out.print( "Enter an int value (the program exits if the input is 0): "); data = input.nextInt(); } //end of while System.out.println("The sum is " + sum); } //end of main } //end of class Run Enter an int value (the program exits if the input is 0): 2 Enter an int value (the program exits if the input is 0): 3 Enter an int value (the program exits if the input is 0): 4 Enter an int value (the program exits if the input is 0): 0 The sum is 9

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Initialize count animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is true animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Print Welcome to Java animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Increase count by 1 count is 1 now animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is still true since count is 1 animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Print Welcome to Java animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Increase count by 1 count is 2 now animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is false since count is 2 now animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace while Loop int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } The loop exits. Execute the next statement after the loop. animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing : double item = 1; double sum = 0; while (item != 0) { // No guarantee item will be 0 sum += item; item -= 0.1; } System.out.println(sum); Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed. The loop should terminate when item becomes 0. However, there is no guarantee that item will be exactly 0, because the floating-point arithmetic is approximated. This loop seems OK on the surface, but it is actually an infinite loop.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition); The do-while loop is a variation of the while loop. The syntax below:

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved do While Loop  When to use a do loop: –If you know that the repeated thing will always have to be done at least one time. F Syntax: do { } while ( ); –Note: The condition is at the bottom of the loop (in contrast to the while loop, where the condition is at the top of the loop). –The compiler requires putting a ";" at the very end, after the do loop's condition. –Proper style dictates putting the "while" part on the same line as the "}"

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved The do...while Loop 24 If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false. public class Test2 { public static void main(String args[]){ int x= 10; do { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } while( x < 20 ); } // end of main } //end of class

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved do while Loop // FloorSpace.java – Calculates total floor space in a house import java.util.Scanner; public class FloorSpace { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); double length, width; // room dimensions double floorSpace = 0; // house's total floor space String response; // user's y/n response do { System.out.print("Enter the length: "); length = stdIn.nextDouble(); System.out.print("Enter the width: "); width = stdIn.nextDouble(); floorSpace += length * width; System.out.print("Any more rooms? (y/n): "); response = stdIn.next(); } while (response.equalsIgnoreCase("y")); System.out.println("The total floor space is " + floorSpace); } // end main } // end class

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved for Loops for (initial-action; loop- continuation-condition; action-after-each-iteration) { // loop body; Statement(s); } int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved for Loop  When to use a for loop: –If you know the exact number of loop iterations before the loop begins.  For example, use a for loop to: –Print this countdown from 10. Sample session: Liftoff! –Find the factorial of a user-entered number. Sample session: Enter a whole number: 4 4! = 24

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved for Loop for loop syntax for ( ; ; ) { } for loop example for (int i=10; i>0; i--) { System.out.print(i + " "); } System.out.println("Liftoff!"); for loop semantics: Before the start of the first loop iteration, execute the initialization component. At the top of each loop iteration, evaluate the condition component: If the condition is true, execute the body of the loop. If the condition is false, terminate the loop (jump to the statement below the loop's closing brace). At the bottom of each loop iteration, execute the update component and then jump to the top of the loop.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved for Loop F Trace this code fragment with an input value of 3. Scanner stdIn = new Scanner(System.in); int number; // user entered number double factorial = 1.0; // factorial of user entry System.out.print("Enter a whole number: "); number = stdIn.nextInt(); for (int i=2; i<=number; i++) { factorial *= i; } System.out.println(number + "! = " + factorial); for loop index variables are often, but not always, named i for “index.” Declare for loop index variables within the for loop heading.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. public class Test3 { public static void main(String args[]) { for(int x = 10; x < 20; x = x+1){ System.out.print("value of x : " + x ); System.out.print("\n"); } //end of for loop } //end of main method } // end of class The for loop

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Here is the flow of control in a for loop: The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. for(int x = 10; x<20; x = x + 1); Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. x < 20; // true, then System.out.print("value of x : " + x ); // body of the loop System.out.print("\n"); //body of the for loop // increment the statement and back to checking the condition If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. After the body of the for loop executes, the flow of control jumps back up to the update statement. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved The only thing that can make it faster would be to have less nesting of loops, and looping over less values. The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all. int i = 0; while (i < 20){ // do stuff i++; } Is the same as: for (int i = 0; i < 20; i++){ // do Stuff } ( Actually the for-loop is a little better because the i will be out of scope after the loop while the i will stick around in the while loop case.) A for loop is just a syntactically prettier way of looping For Loop vs. While Loop

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Problem: Guessing Numbers Write a program that randomly generates an integer between 0 and 100, inclusive. The program prompts the user to enter a number continuously until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high, so the user can choose the next input intelligently. Here is a video and sample run: GuessNumber Video Link: Problem Guessing NumbersProblem Guessing Numbers

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved import java.util.Scanner; public class GuessNumber { public static void main(String[] args) { // Generate a random number to be guessed int number = (int)(Math.random() * 101); // static double, random() Returns a double value with a positive sign, greater than or Scanner input = new Scanner(System.in); // scanner breakdown formatting/allocate input and their data type System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) { // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } // End of loop } }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Problem: An Advanced Math Learning Tool The Math subtraction learning tool program generates just one question for each run. You can use a loop to generate questions repeatedly. This example gives a program that generates five questions and reports the number of the correct answers after a student answers all five questions. Video Link: Problem SubtractionQuizLoopProblem SubtractionQuizLoop

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved import java.util.Scanner; public class SubtractionQuizLoop { public static void main(String[] args) { final int NUMBER_OF_QUESTIONS = 5; // Number of questions int correctCount = 0; // Count the number of correct answers int count = 0; // Count the number of questions long startTime = System.currentTimeMillis(); String output = ""; // output string is initially empty Scanner input = new Scanner(System.in); while (count < NUMBER_OF_QUESTIONS) { // 1. Generate two random single-digit integers int number1 = (int)(Math.random() * 10); int number2 = (int)(Math.random() * 10); // 2. If number1 < number2, swap number1 with number2 if (number1 < number2) { int temp = number1; number1 = number2; number2 = temp; } // 3. Prompt the student to answer “What is number1 – number2?” System.out.print( "What is " + number1 + " - " + number2 + "? "); int answer = input.nextInt(); // 4. Grade the answer and display the result if (number1 - number2 == answer) { System.out.println("You are correct!"); correctCount++; } else System.out.println("Your answer is wrong.\n" + number1 + " - " + number2 + " should be " + (number1 - number2)); // Increase the count count++; output += "\n" + number1 + "-" + number2 + "=" + answer + ((number1 - number2 == answer) ? " correct" : " wrong"); } long endTime = System.currentTimeMillis(); long testTime = endTime - startTime; System.out.println("Correct count is " + correctCount + "\nTest time is " + testTime / " seconds\n" + output); } } SubtractionQuizLoop

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Ending a Loop with a Sentinel Value Another technique for lop control is to designate a special value. Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a special input values is known as a sentinel value. Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. SentinelValue

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Declare i animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Execute initializer i is now 0 animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } (i < 2) is true since i is 0 animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Print Welcome to Java animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Execute adjustment statement i now is 1 animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } (i < 2) is still true since i is 1 animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Print Welcome to Java animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Execute adjustment statement i now is 2 animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } (i < 2) is false since i is 2 animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Exit the loop. Execute the next statement after the loop animation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Note The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each- iteration in a for loop can be a list of zero or more comma- separated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however. for (int i = 1; i < 100; System.out.println(i++)); for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion:

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: Logic Error for (int i=0; i<10; i++); { System.out.println("i is " + i); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Caution, cont. Similarly, the following loop is also wrong: int i=0; while (i < 10); { System.out.println("i is " + i); i++; } In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System.out.println("i is " + i); i++; } while (i<10); Logic Error Correct

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved The only thing that can make it faster would be to have less nesting of loops, and looping over less values. The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all. int i = 0; while (i < 20){ // do stuff i++; } Is the same as: for (int i = 0; i < 20; i++){ // do Stuff } ( Actually the for-loop is a little better because the i will be out of scope after the loop while the i will stick around in the while loop case.) A for loop is just a syntactically prettier way of looping For Loop vs. While Loop

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Which Loop to Use? The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b): A for loop in (a) in the following figure can generally be converted into the following while loop in (b) except in certain special cases (see Review Question 3.19 for one of them):

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Recommendations Use the one that is most intuitive and comfortable for you. o In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. o A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0 (use counter). o A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Loop Comparison for loop: do loop: while loop: When to use If you know, prior to the start of loop, how many times you want to repeat the loop. If you always need to do the repeated thing at least one time. If you can't use a for loop or a do loop. Template for (int i=0; i<max; i++) { } do { } while ( ); while ( ) { }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Nested Loops F Nested loops = a loop within a loop. F Example – Write a program that prints a rectangle of characters where the user specifies the rectangle's height, the rectangle's width, and the character's value. Sample session: Enter height: 4 Enter width: 3 Enter character: < <<<

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Nested Loops import java.util.Scanner; public class RecAngle1 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int height, width; // rectangle's dimensions char printCharacter; // this character forms the rectangle System.out.print("Enter height: "); height = stdIn.nextInt(); System.out.print("Enter width: "); width = stdIn.nextInt(); System.out.print("Enter character: "); printCharacter = stdIn.next().charAt(0); for (int row=1; row<=height; row++) { for (int col=1; col<=width; col++) { System.out.print(printCharacter); } //end of nested for System.out.println(); } //end of for } // end main } // end class Rectangle

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Boolean Variables F Programs often need to keep track of the state of some condition. F For example, if you're writing a program that simulates the operations of a garage door opener, you'll need to keep track of the state of the garage door's direction and the direction up or down? F You need to keep track of the direction "state" because the direction determines what happens when the garage door opener's button is pressed. F If the direction state is up, then pressing the garage door button causes the direction to switch to down. F If the direction state is down, then pressing the garage door button causes the direction to switch to up.  To implement the state of some condition, use a boolean variable.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Nested Loops Problem: Write a program that uses nested for loops to print a multiplication table. MultiplicationTable public class MultiTable { /** Main method */ public static void main(String[] args) { // Display the table heading System.out.println(" Multiplication Table"); // table title – display a title on the first line in the output // Display the number title System.out.print(" "); for (int j = 1; j <= 9; j++) //this for loop display the numbers 1 through 9 on the second line. System.out.print(" " + j); System.out.println("\n "); // the dash (-) line displayed on the third line // Print table body for (int i = 1; i <= 9; i++) { //outer loop with the control variable i in the outer loop System.out.print(i + " | "); for (int j = 1; j <= 9; j++) { // Display the product and align properly //inner loop with the control variable j in the inner loop System.out.printf("%4d", i * j); // for each I, the product I * j is displayed on a line in the inner loop. } //with j begin 1, 2, 3, …9. System.out.println(); } } }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Minimizing Numerical Errors Numeric errors involving floating-point numbers are expected. This section discusses how to minimize such errors through an example. Listing 4.7. Here is an example that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: and so on. public class TestSum { public static void main(String[] args) { // Initialize sum float sum = 0; // Add 0.01, 0.02,..., 0.99, 1 to sum for (float i = 0.01f; i <= 1.0f; i = i f) sum += i; // Display result System.out.println("The sum is " + sum); } } TestSum Video Link: Problem TestSum Problem TestSum

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Problem: Finding the Greatest Common Divisor Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. GreatestCommonDivisorRun

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved import java.util.Scanner; public class GreatestCommonDivisor { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter first integer: "); int n1 = input.nextInt(); System.out.print("Enter second integer: "); int n2 = input.nextInt(); int gcd = 1; int k = 2; while (k <= n1 && k <= n2) { if (n1 % k == 0 && n2 % k == 0) gcd = k; k++; } System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd); } }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Problem: Predicating the Future Tuition- Listing 4.9 double tuition = 10000; int year = 1 // Year 1 tuition = tuition * 1.07; year++; // Year 2 tuition = tuition * 1.07; year++; // Year 3 tuition = tuition * 1.07; year++; // Year 4... FutureTuitionRun

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Problem: Predicating the Future Tuition Problem: Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every year. In how many years will the tuition be doubled? Before you write this program try to solve this problem first by hand. FutureTuition Run public class FutureTuition { public static void main(String[] args) { double tuition = 10000; // Year 1 int year = 1; while (tuition < 20000) { tuition = tuition * 1.07; year++; } System.out.println("Tuition will be doubled in " + year + " years"); } }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Problem: Monte Carlo Simulation The Monte Carlo simulation refers to a technique that uses random numbers and probability to solve problems. This method has a wide range of applications in computational mathematics, physics, chemistry, and finance. This section gives an example of using the Monte Carlo simulation for estimating . Assume the radius of the Circle is 1, area is  and the square area is 4. MonteCarloSimulation Run circleArea / squareArea =  / 4.  can be approximated as 4 * numberOfHits /

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved public class MonteCarloSimulation { public static void main(String[] args) { final int NUMBER_OF_TRIALS = ; int numberOfHits = 0; for (int i = 0; i < NUMBER_OF_TRIALS; i++) { double x = Math.random() * ; double y = Math.random() * ; if (x * x + y * y <= 1) numberOfHits++; } //end of while double pi = 4.0 * numberOfHits / NUMBER_OF_TRIALS; System.out.println("PI is " + pi); } // end of main method } //end of class Problem: Monte Carlo Simulation Web link: Class MathClass Math Web Link: About Monte Carlo Simulation - IntroductionAbout Monte Carlo Simulation - Introduction

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Using break and continue Examples for using the break and continue keywords that can be used in loop statements to provide additional controls. F TestBreak.java // you have to used the keyword break in a switch statement // you can use break in a loop to immediately terminate the loop. F TestContinue.java TestBreak TestContinue

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Guessing Number Problem Revisited Here is a program for guessing a number. You can rewrite it using a break statement. Listing 4.11 public class TestBreak { public static void main(String[] args) { int sum = 0; int number = 0; while (number = 100) break; // goes to println } System.out.println("The number is " + number); System.out.println("The sum is " + sum); } } GuessNumberUsing Break

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Guessing Number Problem Revisited Here is a program for guessing a number. You can rewrite it using a continue statement. Listing 4.12 public class TestContinue { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; if (number == 10 || number == 11) continue; sum += number; } //end of while System.out.println("The sum is " + sum); } //end of main method } //end of class Test Continue

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Problem: Displaying Prime Numbers Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Solution: The problem can be broken into the following tasks: For number = 2, 3, 4, 5, 6,..., test whether the number is prime. Determine whether a given number is prime. Count the prime numbers. Print each prime number, and print 10 numbers per line. PrimeNumberRun

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Exercise 4_22 Financial application: Loan repayment schedule 71 Video Link: Exercise 4_22Exercise 4_22 Please refer to companion website for the program.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved (GUI) Controlling a Loop with a Confirmation Dialog A sentinel-controlled loop can be implemented using a confirmation dialog. The answers Yes or No to continue or terminate the loop. The template of the loop may look as follows: int option = 0; while (option == JOptionPane.YES_OPTION) { System.out.println("continue loop"); option = JOptionPane.showConfirmDialog(null, "Continue?"); } SentinelValueUsingConfirmationDialogRun