Chapter 5 Conditionals and Loops Conditionals and Loops




























































- Slides: 60

Chapter 5 Conditionals and Loops

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 2

Outline The while Statement Iterators Other Repetition Statements © 2004 Pearson Addison-Wesley. All rights reserved 3

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 reserved 4

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 5

Logic of a while Loop condition evaluated true false statement © 2004 Pearson Addison-Wesley. All rights reserved 6

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 reserved 7

The while Repetition Structure • Flowchart of while loop int product = 2; while ( product <= 1 product = 2 * pro int product = 2 true product <= 1000 product = 2 * product false © 2004 Pearson Addison-Wesley. All rights reserved 8

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 reserved 9

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 reserved 10

while loop format • Sum the numbers from 1 to 100 © 2004 Pearson Addison-Wesley. All rights reserved 11

while loop format • Determine how many students of 10 pass and fail System. out. print("Enter result(1 = pass, 2 = fail): "); result = scan. next. Int(); © 2004 Pearson Addison-Wesley. All rights reserved 12

Two Basic Kinds of Loops • Count controlled § § Example: • Event controlled § § Example: • Combine the two types § Example: © 2004 Pearson Addison-Wesley. All rights reserved 13

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) • A loop can also be used for input validation, making a program more robust • See Win. Percentage. java (page 231) 14

Average. java System. out. print ("Enter an integer (0 to quit): "); value = scan. next. Int(); 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. next. Int(); } © 2004 Pearson Addison-Wesley. All rights reserved 15

Average. java System. out. println (); if (count == 0) System. out. println ("No values were entered. "); else { average = (double)sum / count; Decimal. Format fmt = new Decimal. Format ("0. ###"); System. out. println ("The average is " + fmt. format(average)); } } } © 2004 Pearson Addison-Wesley. All rights reserved 16

Win. Percent. java System. out. print ("Enter the number of games won (0 to " + NUM_GAMES + "): "); won = scan. next. Int(); while (won < 0 || won > NUM_GAMES) { System. out. print ("Invalid input. Please reenter: "); won = scan. next. Int(); } ratio = (double)won / NUM_GAMES; Number. Format fmt = Number. Format. get. Percent. Instance(); System. out. println ("Winning percentage: " + fmt. format(ratio)); © 2004 Pearson Addison-Wesley. All rights reserved 17

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 reserved 18

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 19

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 reserved 20

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 Palindrome. Tester. java (page 235) © 2004 Pearson Addison-Wesley. All rights reserved 21

Palindrome. Tester. java while (another. equals. Ignore. Case("y")) // allows y or Y { System. out. println ("Enter a potential palindrome: "); str = scan. next. Line(); left = 0; right = str. length() - 1; while (str. char. At(left) == str. char. At(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. next. Line(); } © 2004 Pearson Addison-Wesley. All rights reserved 22

Nested Loops • How many times will the string "Here" be printed? count 1 = 1; while (count 1 <= 10) { count 2 = 1; while (count 2 <= 20) { System. out. println ("Here"); count 2++; } count 1++; } © 2004 Pearson Addison-Wesley. All rights reserved 23

Outline The while Statement Iterators Other Repetition Statements © 2004 Pearson Addison-Wesley. All rights reserved 24

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 has. Next 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 reserved 25

Iterators • Several classes in the Java standard class library are iterators • The Scanner class is an iterator § the has. Next 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 has. Next method for specific data types (such as has. Next. Int) © 2004 Pearson Addison-Wesley. All rights reserved 26

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) © 2004 Pearson Addison-Wesley. All rights reserved 27

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 file. Scan, url. Scan; file. Scan = new Scanner (new File("urls. inp")); © 2004 Pearson Addison-Wesley. All rights reserved 28

URLDissector. java // Read and process each line of the file while (file. Scan. has. Next()) { url = file. Scan. next. Line(); System. out. println ("URL: " + url); url. Scan = new Scanner (url); url. Scan. use. Delimiter("/"); // Print each part of the url while (url. Scan. has. Next()) System. out. println (" " + url. Scan. next()); System. out. println(); } } } © 2004 Pearson Addison-Wesley. All rights reserved 29

Sample Run Input file: urls. inp Output URL: www. google. com URL: java. sun. com/j 2 se/1. 5 java. sun. com www. linux. org/info/gnu. html j 2 se duke. csc. villanova. edu/lewis/ www. csc. villanova. edu/academics/index. jsp 1. 5 URL: www. linux. org/info/gnu. html www. linux. org info gnu. html URL: duke. csc. villanova. edu/lewis/ duke. csc. villanova. edu lewis URL: www. csc. villanova. edu/academics/index. jsp www. csc. villanova. edu academics index. jsp © 2004 Pearson Addison-Wesley. All rights reserved 30

Outline The while Statement Iterators Other Repetition Statements © 2004 Pearson Addison-Wesley. All rights reserved 31

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 reserved 32

Logic of a do Loop statement true condition evaluated false © 2004 Pearson Addison-Wesley. All rights reserved 33

The do Statement • An example of a do loop: int count = 0; do { count++; System. out. println (count); } while (count < 5); • The body of a do loop executes at least once • See Reverse. Number. java (page 244) © 2004 Pearson Addison-Wesley. All rights reserved 34

Reverse. Number. java System. out. print ("Enter a positive integer: "); number = scan. next. Int(); do { last. Digit = number % 10; reverse = (reverse * 10) + last. Digit; number = number / 10; } while (number > 0); System. out. println ("That number reversed is " + reverse); Output Enter a positive integer: 13667 That number reversed is 76631 © 2004 Pearson Addison-Wesley. All rights reserved 35

Comparing while and do The while Loop The do Loop statement condition evaluated true statement © 2004 Pearson Addison-Wesley. All rights reserved true false condition evaluated false 36

The for Statement • A for statement has the following syntax: The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration © 2004 Pearson Addison-Wesley. All rights reserved 37

Logic of a for loop initialization condition evaluated true false statement increment © 2004 Pearson Addison-Wesley. All rights reserved 38

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 reserved 39

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 reserved 40

The for Statement • The increment section can perform any calculation for (int num=100; num > 0; num -= 5) System. out. println (num); • 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) • See Stars. java (page 250) © 2004 Pearson Addison-Wesley. All rights reserved 41

Multiples. java System. out. print ("Enter a positive value: "); value = scan. next. Int(); System. out. print ("Enter an upper limit: "); limit = scan. next. Int(); 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 reserved 42

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 reserved 43

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 reserved 44

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 reserved 45

Loops to watch out for • for loop order to operation 1. 2. 3. 4. 5. 6. 7. 8. • initialization test statements increment test for ( initialization; test; increment ) statement How many times is the loop body repeated? § § for (int i = 10; i < 0; i++) for (int i = 0; i < 10; i--) © 2004 Pearson Addison-Wesley. All rights reserved 46

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 reserved 47

Exercise • What mathematical result does the following fragment compute and display? System. out. print("Enter x: "); int x = scan. next. Int(); System. out. print("Enter y: "); int y. First = scan. next. Int(); int product = 1; for (int y = y. First; y > 0; y--) product *= x; System. out. println(“result = “ + product); © 2004 Pearson Addison-Wesley. All rights reserved 48

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 reserved 49

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 reserved 50

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 reserved 51

Basic Series double accumulator = 0; for (int i = 1; i <= number. Of. Terms; i++) accumulator += Term(i) § where Term(i) is a function (or expression) that computes the ith term. • Example § Harmonic series H = 1 + 1/2 + 1/3 + 1/4 + 1/5 +. . . § © 2004 Pearson Addison-Wesley. All rights reserved 52

Computing the ith term • Given a series, you can usually write a loop like this quickly if you can figure out the ith term § some books directly give you the ith term • For example, what’s the ith term for this series? § S = 1 + 1/2 + 1/4 + 1/8 + 1/16 + 1/32 +. . . § © 2004 Pearson Addison-Wesley. All rights reserved 53

Writing loops for series • Write a loop for the series • © 2004 Pearson Addison-Wesley. All rights reserved 54

More Complicated Series • Compute alternating signs § use an accumulator that you multiply by -1; this changes the sign. § 1– 2+3– 4+5– 6… © 2004 Pearson Addison-Wesley. All rights reserved 55

More Complicated Series • Write a loop that outputs odd (or even) numbers § Output the first n odd integers © 2004 Pearson Addison-Wesley. All rights reserved 56

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 sign = sign * -1; } © 2004 Pearson Addison-Wesley. All rights reserved “ + pi ); 57

Practice Problems • The triangular numbers § 1, 3, 6, 10, 15, 21, 28. . . • Calculate the sine function § © 2004 Pearson Addison-Wesley. All rights reserved 58

Practice Problems • Another way to compute π/4 is with this series: § © 2004 Pearson Addison-Wesley. All rights reserved 59

Summary • Chapter 5 focused on: § § § boolean expressions conditional statements comparing data repetition statements iterators © 2004 Pearson Addison-Wesley. All rights reserved 60