530 likes | 708 Views
Chapter 5: Control Structures II. J ava P rogramming: From Problem Analysis to Program Design,. Chapter Objectives. Learn about repetition (looping) control structures. Explore how to construct and use count-controlled, sentinel-controlled and flag-controlled repetition structures.
E N D
Chapter 5: Control Structures II JavaProgramming: From Problem Analysis to Program Design,
Chapter Objectives • Learn about repetition (looping) control structures. • Explore how to construct and use count-controlled, sentinel-controlled and flag-controlled repetition structures. • Examine break and continue statements. • Discover how to form and use nested control structures.
Why Is Repetition Needed? How can you solve the following problem: • What is the sum of all the numbers from 1 to 100. • The answer will be 1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100.
Why Is Repetition Needed? Here’s some sample Java code: int sum=0; sum = sum+1; sum = sum +2; sum = sum +3; sum = sum +4; … sum = sum +99; sum = sum +100; System.out.println(“The sum from 1 to 100 = “ +sum);
Why Is Repetition Needed? This solution has two major problems. • Firstly, it’s tedious and it would take a long time to type in. There is also a high risk of making an error while typing it in. • Secondly, it doesn’t easily scale. This may work for 100 numbers but how would you handle having to add from 1 to a 1000? Or to 1000000?Or to 1000000000?
Why Is Repetition Needed? Develop the Algorithm • Create a variable to hold the sum. • Initialise the sum to zero. • Create a variable to hold a counter from 1 to 100. • Initialise the counter to 1. • While the counter is less-than-or-equal to 100 • add the counter to the sum • add one to the counter • Now repeat • Print the sum
Why Is Repetition Needed? We can use pseudo-code notation to make this less vague. sum = 0 count = 1 loop while count <= 100 sum = sum + count count++ endloop print sum • THIS IS NOT JAVA! This is only pseudo-code and won’t compile.
Why Is Repetition Needed? loop while condition <body> endloop • This pseudo-code means: before executing the statements in the body, evaluate the condition. If the condition is true then execute the body once. • Once you have executed the body statements once, go back to the loop condition and re-evaluate it. If it is true, execute the body code again. If the condition is not true then the body will not be executed!
The while Looping (Repetition) Structure • Now we need to turn our pseudo-code into Java. • Java has 3 repetition structures: while, for and do … while. • One way Java supports repetition is using While statements. • Syntax: while (expression) { // body statements } • The expression MUST be placed inside parentheses. • As with an if statement, the expression part is evaluated to determine whether or not the statements should be executed. • The body of the loop is enclosed in { and }.
The while Looping (Repetition) Structure • public class FirstLoop • { • public static void main(String[] args) • { • int sum = 0; • int count = 1; • while (count <= 100) { • sum = sum + count; • count++; • } • System.out.println("Sum = “ + sum); • } • }
The while Looping (Repetition) Structure • Infinite loop: is a loop that continues to execute endlessly. • So, expression is always true in an infinite loop. • Statements must change value of expression to false.
The while Looping (Repetition) Structure i is called LCV Example 5-1 i = 0; //Line 1 while (i <= 20) //Line 2 { System.out.print(i + " "); //Line 3 i = i + 5; //Line 4 } System.out.println(); //Line 5 Output 0 5 10 15 20 What is the value of i at the end? What will happen if you omit i= i + 5; ? What will happen if you omit i =0; ?
The while Looping (Repetition) Structure Typically, while loops are written in the following form: //initialize the loop control variable(s) while (expression) //expression tests the LCV { . . . //update the loop control variable(s) . . . }
Counter-Controlled while Loop • Used when exact number of data or entry pieces is known. • General form: int N = //value input by user or specified //in program int counter = 0; while (counter < N) { . . . counter++; . . . }
Counter-Controlled while Loop Example5_3 import java.util.*;public classExample5_3{static Scanner console = new Scanner(System.in);public static void main (String[] args) {int limit; //store the number of items //in the listint number; //variable to store the numberint sum; //variable to store the sumint counter; //loop control variable System.out.println("Line 1: Enter data for " + "processing"); //Line 1 limit =console.nextInt(); //Line 2 sum = 0; //Line 3counter = 0;//Line 4
Counter-Controlled while Loop Example5_3 while(counter <limit) //Line 5 { number = console.nextInt(); //Line 6 sum = sum + number; //Line 7counter++;//Line 8 } System.out.printf("Line 9: The sum of the %d " + " numbers = %d%n",limit, sum); //Line 9if(counter != 0) //Line 10 System.out.printf("Line 11: The average = %d%n", (sum / counter)); //Line 11else //Line 12 System.out.println("Line 13: No input."); //Line 13 }} Line 1: Enter data for processing 12 8 9 2 3 90 38 56 8 23 89 7 2 8 3 8 Line 9: The sum of the 12 numbers = 335 Line 11: The average = 27
Sentinel-Controlled while Loop • Used when exact number of entry pieces is unknown, but last entry (special/sentinel value) is known. • General form: Input the first data item into variable; while (variable != sentinel) { . . . input a data item into variable; . . . }
Sentinel-Controlled while Loop Example5_4 Line 1: Enter positive integers ending with -999 34 23 9 45 78 0 77 8 3 5 -999 Line 7: The sum of 10 numbers = 282 Line 9: The average = 28 import java.util.*;public class Example5_4{ static Scanner console = new Scanner(System.in); static final int SENTINEL = -999; public static void main (String[] args) { int number; int sum = 0; int count = 0; System.out.println("Line 1: Enter positive integers " + "ending with "+ SENTINEL); number = console.nextInt(); while( number != SENTINEL) { sum = sum + number; count++; number = console.nextInt(); } System.out.println("Line 7: The sum of " + count + " numbers = " + sum); if(count != 0) System.out.println("Line 9: The average = " + (sum / count)); else System.out.println("Line 11: No input."); }}
Flag-Controlled while Loop • Boolean value used to control loop. • General form: boolean found = false; //initialize LCV while (!found) // test LCV { . . . if (expression) found = true; //update LCV . . . }
Input - Controlled while Loop • Sentinel value is not always appropriate, programmer sometimes does not know what sentinel is. • In this situation, we can use the input- controlled while loop structure. • console acts as LCV. • The method hasNext, of the classScanner, returns true if there is an input in the input stream; otherwise, it returns false. • The expression console.hasNext() acts as the loop condition. • Expressions such as console.nextInt() update the value of the loop condition.
Input - Controlled while Loop • A general form of the input - controlled while loop that uses the Scanner object console to input data is: while (console.hasNext()) { //Get the next input and store it in an //appropriate variable //Process data }
Input - Controlled while Loop Example5_7 Enter numbers then press Ctrl key and press z: 2 4 5<eof> Sum = 11 import java.util.*; public class Example5_7{ static Scanner console = new Scanner(System.in); public static void main (String[] args) { int num; int sum = 0; System.out.println("Enter numbers then press Ctrl key and press z: "); while(console.hasNext()) { num = console.nextInt(); sum = sum + num; } System.out.printf("Sum = %d%n", sum); }}
Programming Example: Fibonacci Number • Fibonacci formula for any Fibonacci sequence: an = an-1 + an-2 • Input: First two Fibonacci numbers in sequence, position in sequence of desired Fibonacci number (n). • intprevious1 = Fibonacci number 1 • intprevious2 = Fibonacci number 2 • intnthFibonacci = Position of nth Fibonacci number • Output: nth Fibonacci number.
Programming Example: Fibonacci Number (Solution) if (nthFibonacci == 1) current = previous1; else if (nthFibonacci == 2) current = previous2; else { counter = 3; while (counter <= nthFibonacci) { current = previous2 + previous1; previous1 = previous2; previous2 = current; counter++; } } • Final result found in last value of current.
The for Looping (Repetition) Structure • Specialized form of while loop. • Simplifies the writing of count-controlled loops. • Syntax: for(initial statement; loop condition; update statement) statement
The for Looping (Repetition) Structure • Execution: • Initial statement executes.// only executes once • Loop condition is evaluated. • If loop condition evaluates to true, execute for loop statement and execute update statement. • Repeat until loop condition is false.
The for Looping (Repetition) Structure Example 5-8 The following for loop prints the first 10 positive integers: for (i = 0; i < 10; i++) System.out.print(i + " "); System.out.println(); Output 0 1 2 3 4 5 6 7 8 9
The for Looping (Repetition) Structure Hello * Hello * Hello * Hello * Hello * Example 5-9 • The following for loop outputs the word Hello and a star (on separate lines) five times: for (i = 1; i <= 5; i++) { System.out.println("Hello"); System.out.println("*"); } • The following for loop outputs the word Hello five times and the star only once: • for (i = 1; i <= 5; i++) • System.out.println("Hello"); • System.out.println("*"); Hello Hello Hello Hello Hello *
The for Looping (Repetition) Structure Example 5-10 What will the following for loop execute? for ( i = 0; i < 5; ++i); System.out.println(“*”); Check examples 5-11, 5-12, 5-13 for nice ideas when using for loop.
The for Looping (Repetition) Structure • Does not execute if initial condition is false. • Update expression changes value of loop control variable, eventually making it false. • If loop condition is always true, result is an infinite loop. • Infinite loop can be specified by omitting all three control statements: for (;;) System.out.println(“Hello”); //infinite loop printing Hello • If loop condition is omitted, it is assumed to be true. • for statement ending in semicolon is empty.
Programming Example: Classify Numbers • Input: Nintegers (positive, negative, and zeros). int N = 20; //N easily modified • Output: Number of 0s, number of even integers, number of odd integers.
Programming Example: Classify Numbers (Solution) for (counter = 1; counter <= N; counter++) { number = console.nextInt(); System.out.print(number + " "); switch (number % 2) { case 0: evens++; if (number == 0) zeros++; break; case 1: case -1: odds++; } //end switch } //end for loop
The do…while Loop (Repetition) Structure • Syntax: do statement while(expression); • Statements are executed first and then expression is evaluated. • Statements are executed at least once and then continued if expression is true.
do…while Loop (Post-Test Loop) • In a while or for loop: condition is evaluated before executing the body of the loop pre-test loops. • In a do … while loop: condition is evaluated after executing the body of the loop post-test loop.
do…while Loop (Post-Test Loop) Example 5-16: what does each loop produce? (a) i = 11; while(i <= 10) { System.out.print(i + " "); i = i + 5; } System.out.println(); (b) i = 11; do { System.out.print(i + " "); i = i + 5; } while(i <= 10); System.out.println(); 11
do…while Loop (Post-Test Loop) When is do…while loop useful ?? Check example 5-17 to figure out!
Note… • All three loops: while, foranddo…whilehave their place in Java. One loop can often replace another. • For example do..while loop can replace while loop as follow: if (expression) do action while(expression); • Replaces: while (expression) action
break Statements • Used to exit early from a loop. • Used to skip remainder of switch structure. • Can be placed within if statement of a loop. • If condition is met, loop is exited immediately.
break Statements Example: Find the sum of a set of positive numbers, if the data set contains a negative number stop summing. sum = 0; while(console.hasNext()) { num = console.nextInt(); if(num < 0) //if number is negative, terminate the loop { System.out.println("Negative number found in data"); break; } sum= sum + num; }
continue Statements • Used in while, for, and do...while structures. • When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop. • When executed in a while/do…while structure, expression is evaluated immediately after continue statement. • In a for structure, the update statement is executed after the continue statement; the loop condition then executes.
continue Statements Example: Find the sum of a set of positive numbers, if a negative number appears in the data set skip it and read the following number. sum = 0; while(console.hasNext()) { num = console.nextInt(); if(num < 0) //if number is negative, read next number { System.out.println("Negative number found in data"); continue; } sum= sum + num; }
Nested Control Structures • Provides new power, subtlety, and complexity. • if, if…else, and switch structures can be placed within while loops. • for loops can be found within other for loops.
Nested Control Structures (Example) for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) System.out.print("*"); System.out.println(); } Output: * ** *** **** ***** Check the rest of the text book examples!
Overall guidelines for loops • If you know in advance how many times the loop has to iterate - use a for loop. • Never change the counter variable of a for loop in the loop body - you can get some strange results. • For while and do…while loops, make sure that the variable you are checking in the condition is the same variable that you are changing in the loop body. • Finally, be aware of infinite loops!
Examples public class Example5_6 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int num, guess; boolean done = false; num = (int) (Math.random() * 100); while (!done){ System.out.println("Enter an integer number between 0 and 100"); guess = console.nextInt(); if ( guess == num) { System.out.println("you guessed the correct number \n"); done = true; } else if ( guess < num ) System.out.println("your guess is lower than the number. \nGuess Again."); else System.out.println("your guess is higher than the number. \nGuess Again."); } // end while } //end main }//end class Example 5-6: Guessing the number game
Example 5-6: Sample Run Examples Enter an integer number between 0 and 100 2 your guess is lower than the number. Guess Again. Enter an integer number between 0 and 100 30 your guess is higher than the number. Guess Again. Enter an integer number between 0 and 100 10 your guess is higher than the number. Guess Again. Enter an integer number between 0 and 100 1 your guess is lower than the number. Guess Again. Enter an integer number between 0 and 100 3 you guessed the correct number
Math.random() • syntax Math.random(); • Does not take any parameters, • Returns a random double between 0.0 and 1.0 but not including 1.0. • So for example if you wanted a random number from 0 to 10 you would do the following: int randomNumber = ((int)Math.random()*10)
Examples What is the output of the following loops? • for ( i =5 ; i >=1; i--) System.out.print( i + “ “ ); • for ( i =0; i < 10 ; i+=2) System.out.print( i + “ “ ); • for (i=1; ; i++) System.out.print( i + “ “ ); • for (int i = 5; i <= 1; i--) { for (int j = 1; j <= i; j++) System.out.print(" *"); System.out.println(); }
Examples Trace the following segment: suppose input: 38 45 71 4 -1 sum = console.nextInt(); num = console.nextInt(); while ( num != -1 ) { sum +=num; num = console.nextInt(); } System.out.println(“ Sum = “ + sum);