Chapter 5 Conditionals and Loops
© 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements that allow us to: repeat processing steps in a loop Chapter 5 focuses on: Last Time boolean expressions conditional statements comparing data Today repetition statements iterators
© 2004 Pearson Addison-Wesley. All rights reserved5-3 Outline The while Statement Iterators Other Repetition Statements
© 2004 Pearson Addison-Wesley. All rights reserved5-4 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: the while loop the do loop the for loop The programmer should choose the right kind of loop for the situation
© 2004 Pearson Addison-Wesley. All rights reserved5-5 The while Statement A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false
© 2004 Pearson Addison-Wesley. All rights reserved5-6 Logic of a while Loop statement true false condition evaluated
© 2004 Pearson Addison-Wesley. All rights reserved5-7 The while Statement An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times
© 2004 Pearson Addison-Wesley. All rights reserved5-8 The while Repetition Structure Flowchart of while loop product <= 1000 product = 2 * product true false int product = 2 int product = 2; while ( product <= 1000 ) product = 2 * product; int product = 2; while ( product <= 1000 ) product = 2 * product;
© 2004 Pearson Addison-Wesley. All rights reserved5-9 Parts of a while loop int x = 1; while (x < 10) { System.out.println(x); x++; } Label the following loop int product = 2; while ( product <= 1000 ) product = 2 * product;
© 2004 Pearson Addison-Wesley. All rights reserved5-10 Another loop example Label the parts of the loop int x = 1; int y = 2; while (x < 10) { System.out.println(x + “ “ + y); y *= 2; x++; }
© 2004 Pearson Addison-Wesley. All rights reserved5-11 while loop format Sum the numbers from 1 to 100
© 2004 Pearson Addison-Wesley. All rights reserved5-12 while loop format Determine how many students of 10 pass and fail System.out.print(" Enter result(1 = pass, 2 = fail): "); result = scan.nextInt();
© 2004 Pearson Addison-Wesley. All rights reserved5-13 Two Basic Kinds of Loops Count controlled Example: Event controlled Example: Combine the two types Example:
© 2004 Pearson Addison-Wesley. All rights reserved5-14 The while Statement Let's look at some examples of loop processing A loop can be used to maintain a running sum A sentinel value is a special input value that represents the end of input See Average.java (page 229)Average.java A loop can also be used for input validation, making a program more robust See WinPercentage.java (page 231)WinPercentage.java
© 2004 Pearson Addison-Wesley. All rights reserved5-15 Average.java System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); while (value != 0) // sentinel value of 0 to // terminate loop { count++; sum += value; System.out.println ("The sum so far is " + sum); System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); }
© 2004 Pearson Addison-Wesley. All rights reserved5-16 Average.java System.out.println (); if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count; DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); }
© 2004 Pearson Addison-Wesley. All rights reserved5-17 WinPercent.java System.out.print ("Enter the number of games won (0 to " + NUM_GAMES + "): "); won = scan.nextInt(); while (won NUM_GAMES) { System.out.print ("Invalid input. Please reenter: "); won = scan.nextInt(); } ratio = (double)won / NUM_GAMES; NumberFormat fmt = NumberFormat.getPercentInstance(); System.out.println (); System.out.println ("Winning percentage: " + fmt.format(ratio));
© 2004 Pearson Addison-Wesley. All rights reserved5-18 Print series or table // print i and i 2 while (i < 100) { } Sum series // sum numbers 0 to 99 // int can’t hold this number while (i < 100) { }
© 2004 Pearson Addison-Wesley. All rights reserved5-19 Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally
© 2004 Pearson Addison-Wesley. All rights reserved5-20 Infinite Loops An example of an infinite loop: int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } This loop will continue executing until interrupted (Control-C) or until an underflow error occurs
© 2004 Pearson Addison-Wesley. All rights reserved5-21 Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely See PalindromeTester.java (page 235)PalindromeTester.java
© 2004 Pearson Addison-Wesley. All rights reserved5-22 PalindromeTester.java while (another.equalsIgnoreCase("y")) // allows y or Y { System.out.println ("Enter a potential palindrome:"); str = scan.nextLine(); left = 0; right = str.length() - 1; while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.println(); System.out.print ("Test another palindrome (y/n)? "); another = scan.nextLine(); }
© 2004 Pearson Addison-Wesley. All rights reserved5-23 Nested Loops How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; } count1++; }
© 2004 Pearson Addison-Wesley. All rights reserved5-24 Outline The while Statement Iterators Other Repetition Statements
© 2004 Pearson Addison-Wesley. All rights reserved5-25 Iterators An iterator is an object that allows you to process a collection of items one at a time It lets you step through each item in turn and process it as needed An iterator object has a hasNext method that returns true if there is at least one more item to process The next method returns the next item Iterator objects are defined using the Iterator interface, which is discussed further in Chapter 6
© 2004 Pearson Addison-Wesley. All rights reserved5-26 Iterators Several classes in the Java standard class library are iterators The Scanner class is an iterator the hasNext method returns true if there is more data to be scanned the next method returns the next scanned token as a string The Scanner class also has variations on the hasNext method for specific data types (such as hasNextInt )
© 2004 Pearson Addison-Wesley. All rights reserved5-27 Iterators The fact that a Scanner is an iterator is particularly helpful when reading input from a file Suppose we wanted to read and process a list of URLs stored in a file One scanner can be set up to read each line of the input until the end of the file is encountered Another scanner can be set up for each URL to process each part of the path See URLDissector.java (page 240)URLDissector.java
© 2004 Pearson Addison-Wesley. All rights reserved5-28 URLDissector.java //************************************************************* // URLDissector.java Author: Lewis/Loftus // // Demonstrates the use of Scanner to read file input and // parse it // using alternative delimiters. //************************************************************* import java.util.Scanner; import java.io.*; public class URLDissector { // // Reads urls from a file and prints their path components. // public static void main (String[] args) throws IOException { String url; Scanner fileScan, urlScan; fileScan = new Scanner (new File("urls.inp"));
© 2004 Pearson Addison-Wesley. All rights reserved5-29 URLDissector.java // Read and process each line of the file while (fileScan.hasNext()) { url = fileScan.nextLine(); System.out.println ("URL: " + url); urlScan = new Scanner (url); urlScan.useDelimiter("/"); // Print each part of the url while (urlScan.hasNext()) System.out.println (" " + urlScan.next()); System.out.println(); }
© 2004 Pearson Addison-Wesley. All rights reserved5-30 Sample Run URL: URL: java.sun.com/j2se/1.5 java.sun.com j2se 1.5 URL: info gnu.html URL: duke.csc.villanova.edu/lewis/ duke.csc.villanova.edu lewis URL: academics index.jsp java.sun.com/j2se/1.5 duke.csc.villanova.edu/lewis/ Input file: urls.inp Output
© 2004 Pearson Addison-Wesley. All rights reserved5-31 Outline The while Statement Iterators Other Repetition Statements
© 2004 Pearson Addison-Wesley. All rights reserved5-32 The do Statement A do statement has the following syntax: do { statement; } while ( condition ) The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false
© 2004 Pearson Addison-Wesley. All rights reserved5-33 Logic of a do Loop true condition evaluated statement false
© 2004 Pearson Addison-Wesley. All rights reserved5-34 The do Statement An example of a do loop: The body of a do loop executes at least once See ReverseNumber.java (page 244)ReverseNumber.java int count = 0; do { count++; System.out.println (count); } while (count < 5);
© 2004 Pearson Addison-Wesley. All rights reserved5-35 ReverseNumber.java System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); Enter a positive integer: That number reversed is Output
© 2004 Pearson Addison-Wesley. All rights reserved5-36 Comparing while and do statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop
© 2004 Pearson Addison-Wesley. All rights reserved5-37 The for Statement A for statement has the following syntax: for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration
© 2004 Pearson Addison-Wesley. All rights reserved5-38 Logic of a for loop statement true condition evaluated false increment initialization
© 2004 Pearson Addison-Wesley. All rights reserved5-39 The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }
© 2004 Pearson Addison-Wesley. All rights reserved5-40 The for Statement An example of a for loop: for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times
© 2004 Pearson Addison-Wesley. All rights reserved5-41 The for Statement The increment section can perform any calculation A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance See Multiples.java (page 248)Multiples.java See Stars.java (page 250)Stars.java for (int num=100; num > 0; num -= 5) System.out.println (num);
© 2004 Pearson Addison-Wesley. All rights reserved5-42 Multiples.java System.out.print ("Enter a positive value: "); value = scan.nextInt(); System.out.print ("Enter an upper limit: "); limit = scan.nextInt(); System.out.println (); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:"); for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t"); // Print a specific number of values // per line of output count++; if (count % PER_LINE == 0) System.out.println(); }
© 2004 Pearson Addison-Wesley. All rights reserved5-43 Stars.java // // Prints a triangle shape using asterisk (star) // characters. // public static void main (String[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) System.out.print ("*"); System.out.println(); }
© 2004 Pearson Addison-Wesley. All rights reserved5-44 The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed
© 2004 Pearson Addison-Wesley. All rights reserved5-45 for loop Exercises How many times is the loop body repeated? for (int x = 3; x <= 15; x += 3) System.out.println(x); for (int x = 1; x <= 5; x += 7) System.out.println(x); for (int x = 12; x >= 2; x -= 3) System.out.println(x); Write the for statement that print the following sequences of values. 1, 2, 3, 4, 5, 6, 7 3, 8, 13, 18, 23 20, 14, 8, 2, -4, -10 19, 27, 35, 43, 51
© 2004 Pearson Addison-Wesley. All rights reserved5-46 Loops to watch out for for loop order to operation 1.initialization 2.test 3.statements 4.increment 5.test 6.statements 7.increment 8.test How many times is the loop body repeated? for (int i = 10; i < 0; i++) for (int i = 0; i < 10; i--) for ( initialization; test; increment ) statement
© 2004 Pearson Addison-Wesley. All rights reserved5-47 Exercise How many times is the following loop body repeated? What is printed during each repetition of the loop body and after exit? x = 3; for (int count = 0; count < 3; count++) { x = x * x; System.out.println(x); } System.out.println(x);
© 2004 Pearson Addison-Wesley. All rights reserved5-48 Exercise What mathematical result does the following fragment compute and display? System.out.print("Enter x: "); int x = scan.nextInt(); System.out.print("Enter y: "); int yFirst = scan.nextInt(); int product = 1; for (int y = yFirst; y > 0; y--) product *= x; System.out.println(“result = “ + product);
© 2004 Pearson Addison-Wesley. All rights reserved5-49 Nested loops. What do these print? for (int i = 1; i < 4; i++) for (int j = 1; j < i; j++) System.out.println(i + “ “ + j); for (int i = 0; i < 4; i++) for (int j = 1; j < i; j++) System.out.println(i + “ “ + j); for (int i = 1; i < 4; i++) for (int j = 1; j < i; j++) System.out.println(i + “ “ + j); System.out.println(“******”); int T = 0; for (int i = 1; i < 4; i++) { for (int j = 1; j < 2*i; j += 2) T += j * i; System.out.println(“T = “ + T); }
© 2004 Pearson Addison-Wesley. All rights reserved5-50 Using a loop to find if a number is prime Prime numbers are only divisible by 1 and themselves
© 2004 Pearson Addison-Wesley. All rights reserved5-51 Computing Series A series is a continuing sum of a sequence of terms. Series are used to compute a number of constants and functions It’s useful to know how to write a program to compute one. Challenging at first, you’ll see that they can be attacked by a set of standard techniques.
© 2004 Pearson Addison-Wesley. All rights reserved5-52 Basic Series double accumulator = 0; for (int i = 1; i <= numberOfTerms; i++) accumulator += Term(i) where Term(i) is a function (or expression) that computes the i th term. Example Harmonic series H = 1 + 1/2 + 1/3 + 1/4 + 1/
© 2004 Pearson Addison-Wesley. All rights reserved5-53 Computing the i th term Given a series, you can usually write a loop like this quickly if you can figure out the i th term some books directly give you the i th term For example, what’s the i th term for this series? S = 1 + 1/2 + 1/4 + 1/8 + 1/16 + 1/
© 2004 Pearson Addison-Wesley. All rights reserved5-54 Writing loops for series Write a loop for the series
© 2004 Pearson Addison-Wesley. All rights reserved5-55 More Complicated Series Compute alternating signs use an accumulator that you multiply by -1; this changes the sign. 1 – – – 6 …
© 2004 Pearson Addison-Wesley. All rights reserved5-56 More Complicated Series Write a loop that outputs odd (or even) numbers Output the first n odd integers
© 2004 Pearson Addison-Wesley. All rights reserved5-57 Computation of π by one series Describe the series? double pi = 0; int sign = 1; for (int i= 1; i < 5000; i+= 2) { pi += sign * (4.0 / i); System.out.println( “I “ + i + “ PI “ + pi ); sign = sign * -1; }
© 2004 Pearson Addison-Wesley. All rights reserved5-58 Practice Problems The triangular numbers 1, 3, 6, 10, 15, 21, Calculate the sine function
© 2004 Pearson Addison-Wesley. All rights reserved5-59 Practice Problems Another way to compute π/4 is with this series:
© 2004 Pearson Addison-Wesley. All rights reserved5-60 Summary Chapter 5 focused on: boolean expressions conditional statements comparing data repetition statements iterators