Types of loops Topic 15 � definite loop : A loop that executes a known number of Indefinite Loops - While Loops times. – The for loops we have seen so far are definite loops. We often use "If you cannot grok [understand] the overall language like "repeat _ times" or "for each of these things". – Examples: structure of a program while taking a shower • Repeat these statements 10 times. • Repeat these statements k times. [e.g., with no external memory aids], you are • Repeat these statements for each odd number between 5 and 27. not ready to code it." � indefinite loop : A loop where it is not easily determined in -Rich Pattis advance how many times it will execute. – Indefinite loops often keep looping as long as a condition is true, or until a condition becomes false. – Examples: • Repeat these statements until the user types a valid integer. • Repeat these statements while the number n is not prime. Based on slides for Building Java Programs by Reges/Stepp, found at • Repeat these statements until a factor of n is found. http://faculty.washington.edu/stepp/book/ • Flip a coin until you get 10 flips in a row of the same result CS305j Introduction to While Loops CS305j Introduction to While Loops 1 2 Computing Computing The while loop statement While loop flow chart � The execution of a while loop can be depicted as the following: � The while loop is a new loop statement that is well suited to writing indefinite loops. | V +---------------+ � The while loop, general syntax: +----<---no--| is test true? |--yes--->--+ | +---------------+ | while ( <condition> ) { | ^ V <statement(s)> ; V | +-----------------------------------+ | | | execute the controlled statements | } | | +-----------------------------------+ | ^ | – Example: V | V int number = 1; | | | | +---<-----<-------<-----+ while (number <= 200) { V +-------------------+ System.out.print(number + " "); | execute statement | number *= 2; | after while loop | +-------------------+ } – OUTPUT: 1 2 4 8 16 32 64 128 CS305j Introduction to While Loops 3 CS305j Introduction to While Loops 4 Computing Computing
Example while loop Equivalence of for,while loops � A loop that finds and prints the first factor of a number (other � Any for loop of the following form: than 1): Scanner console = new Scanner(System.in); for ( <initialization> ; <condition> ; <update> ) { System.out.print("Type a number: "); <statement(s)> ; int number = console.nextInt(); } int factor = 2; while (number % factor != 0) { factor++; can be replaced by a while loop of the following form: } System.out.println("First factor: " + factor); <initialization> ; while ( <condition> ) { � OUTPUT: <statement(s)> ; Type a number: 49 First factor: 7 <update> ; } CS305j Introduction to While Loops CS305j Introduction to While Loops 5 6 Computing Computing for/while loop example While loop problem � What while loop is essentially equivalent to the � Write a piece of Java code that uses a while loop to repeatedly prompt the user to type a number until the user types a non-negative number, following for loop? then square it. for (int i = 1; i <= 10; i++) { – Expected output: Type a non-negative integer: -5 System.out.println("Hi there"); Invalid number, try again: -1 } Invalid number, try again: 11 11 squared is 121 � ANSWER: � Solution: System.out.print("Type a non-negative integer: "); int i = 1; int number = console.nextInt(); while (i <= 10) { while (number < 0) { System.out.println("Hi there"); System.out.print("Invalid number, try again: "); number = console.nextInt(); i++; } } int square = number * number; System.out.println(number + " squared is " + square); CS305j Introduction to While Loops 7 CS305j Introduction to While Loops 8 Computing Computing
Square Root Square Root � Recall Heron's method for calculating square � Why 20 iterations? roots Is that enough? � problem: Find sqrt(n) Too many? � Algorithm: public static double squareRoot(double num){ double result = num / 2; 1.Make a guess at the solution. (x 1 ) for(int i = 1; i <= 20; i++){ 2.x 2 = (x 1 + (n / x 1 )) / 2 result = (result + (num / result)) / 2.0; } 3.Repeat for x 3, x 4, x 5, ... return result; Write a Java program that implements } Heron's method to find the square root of 133,579 using 20 iterations of the algorithm. CS305j Introduction to While Loops CS305j Introduction to While Loops 9 10 Computing Computing Square Root Square Root � First Attempt � Rewrite square root using a while loop public static double squareRoot2(double num){ double result = num / 2; � Make initial guess while( result * result != num){ � refine results while result squared is not result = ( result + (num / result)) / 2.0; } equal to num return result; } � Problem. – Recall that variables use a finite amount of memory and are subject to round off and precision errors � Will get stuck in an infinite loop � Define a tolerance and accept results that meet that tolerance CS305j Introduction to While Loops 11 CS305j Introduction to While Loops 12 Computing Computing
Sentinel Loops Example Sentinel Program � Sentinel: a value that signals the end of user Enter an int (-1 to quit): 12 input Enter an int (-1 to quit): 37 � Sentinel loop: a loop that keeps repeating Enter an int (-1 to quit): 42 until the sentinel value is found Enter an int (-1 to quit): 25 � Problem: Enter an int (-1 to quit): 12 – Write a program to read in ints from the user until Enter an int (-1 to quit): 99 they enter -1 to quit. Enter an int (-1 to quit): -1 – Print out the sum and average of the numbers entered Sum of 6 numbers is 227 Average of 6 numbers is 37.833333333333336 CS305j Introduction to While Loops CS305j Introduction to While Loops 13 14 Computing Computing Sentinel Program – First Attempt Sentinel Program – First Attempt � initialize sum, count of numbers, and number public static void main(String[] args){ � while number isn't sentinel value Scanner key = new Scanner(System.in); int sum = 0; – read in a num int count = 0; – add it to sum int number = 0; // anything but -1 while( number != -1 ){ – increment count of numbers System.out.print("Enter an int (-1 to quit): "); � print out sum and average number = key.nextInt(); sum += number; count++; } System.out.println( "Sum of " + count + " numbers is " + sum ); System.out.println( "Average of " + count + " numbers is " + (1.0 * sum / count)); } CS305j Introduction to While Loops 15 CS305j Introduction to While Loops 16 Computing Computing
Sentinel Loop Sentinel Program – First Attempt � Output � What is the problem? – A compiler error? Enter an int (-1 to quit): 12 – A runtime error? Enter an int (-1 to quit): 37 – A logic error? Enter an int (-1 to quit): 42 � We are adding the sentinel to the sum and Enter an int (-1 to quit): 25 counting it as a number Enter an int (-1 to quit): 12 � We need to read N numbers (including the Enter an int (-1 to quit): 99 sentinel value) but only want to use the first Enter an int (-1 to quit): -1 N – 1 Sum of 7 numbers is 226 � A fencepost problem! Average of 7 numbers is 32.285714285714285 CS305j Introduction to While Loops CS305j Introduction to While Loops 17 18 Computing Computing Sentinel Loop Sentinel Loop – Second Attempt � Adding num to sum and incrementing count public static void main(String[] args){ moved to top of the loop Scanner key = new Scanner(System.in); int sum = 0; � Should add an if to ensure program does not int count = 0; System.out.print("Enter an int (-1 to quit): "); divide by 0 int number = key.nextInt(); � Add a constant for the Sentinel to make while( number != -1 ){ sum += number; program more readable count++; System.out.print("Enter an int (-1 to quit): "); number = key.nextInt(); } System.out.println( "Sum of " + count + " numbers is " + sum ); System.out.println( "Average of " + count + " numbers is " + (1.0 * sum / count)); } CS305j Introduction to While Loops 19 CS305j Introduction to While Loops 20 Computing Computing
Recommend
More recommend