Building java programs, chapter 5 Program logic and indefinite loops
Announcements public static int exam1Score() { if (homeworkScore() > 0.80 && notebookCheck() == 1.0 && CompletedExtraAssignedPracticeIts*) { int exam2 = scoreOnExam2(); int exam1 = Math.max(exam1, exam2); return exam1; } * 6 unassigned Practice-It questions from each of the Chapters 3, 4, 5 and 6. Due on the day of the exam 2.
At the end of the class, you will be able to Differentiate between definite and indefinite loops. Understand the syntax of while and do-while loops Use simple while and do-while loops in your own programs
Categories of loops definite loop: Executes a known number of times. – The for loops we have seen are definite loops. Print "hello" 10 times. Find all the prime numbers up to an integer n. Print each odd number between 5 and 127. indefinite loop: The number of times its body repeats is not known in advance. Prompt the user until they type a non-negative number. Print random numbers until a prime number is printed. Repeat until the user has types "q" to quit.
While loop Repeatedly executes its body as long as a logical test is true.
While loop syntax while (test) { statement(s); }
While loop example int num = 1; // initialization while (num <= 200) { // test System.out.print(num + " "); num = num * 2; // update } // output:
Converting for loops to while loops Any for loop of the following form: for ( ; ; ) { ; } can be replaced by a while loop of the following form: ; while ( ) { ; }
Converting for loops to while loops for (int i = 0; i < 10; i++) { System.out.println(i); } int i = 0; while(i < 10) { System.out.println(i); i++; }
Do-while loops Sometimes you want to do your test at the end Example: int sum = 0; do { int num = console.nextInt(); sum += num; // body } while (sum <= 200); // test System.out.print(sum);
Homework for chapter 5 HomeworkAssigned onDue on Read BJP 5.1 and write notes11/04/201411/05/2014 Practice It : SC 1, 2, 3, 411/04/201411/05/2014
At the end of the class, you will be able to Define and write your own Fence-Post and Sentinel loops Define and write your own forever loops Create an object of the Random Class and use its methods
A deceptive problem... Write a method printNumbers that prints each number from 1 to a given maximum, separated by commas. For example, the call: printNumbers(5) should print: 1, 2, 3, 4, 5
Flawed solution 1 public static void printNumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(i + ", "); } System.out.println(); // to end the line of output } – Output from printNumbers(5) : 1, 2, 3, 4, 5,
Flawed solution 2 public static void printNumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line of output } – Output from printNumbers(5) :, 1, 2, 3, 4, 5
Fence post analogy We print n numbers but need only n - 1 commas. Similar to building a fence with wires separated by posts: – If we use a flawed algorithm that repeatedly places a post + wire, the last post will have an extra dangling wire. for (length of fence) { place a post. place some wire. }
Fencepost loop Add a statement outside the loop to place the initial "post." – Also called a fencepost loop or a "loop-and-a-half" solution. place a post. for (length of fence - 1) { place some wire. place a post.}
Fencepost method solution – correct solution public static void printNumbers(int max) { System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); } Alternate solution: Either first or last "post" can be taken out: public static void printNumbers(int max) { for (int i = 1; i <= max - 1; i++) { System.out.print(i + ", "); } System.out.println(max); }
Sentinel loops sentinel: A value that signals the end of input. sentinel loop: Repeats until a sentinel value is seen. Example: Write a program that prompts the user for numbers until the user types -1, then outputs their sum. – (In this case, -1 is the sentinel value.) Enter a number (-1 to quit): 10 Enter a number (-1 to quit): 20 Enter a number (-1 to quit): 30 Enter a number (-1 to quit): -1 The sum is 60
What is wrong with this? Scanner console = new Scanner(System.in); int sum = 0; int number = 1; // "dummy value", anything but -1 while (number != -1) { System.out.print("Enter a number (-1 to quit): "); number = console.nextInt(); sum = sum + number; } System.out.println("The total is " + sum);
Correct solution Scanner console = new Scanner(System.in); int sum = 0; // pull one prompt/read ("post") out of the loop System.out.print("Enter a number (-1 to quit): "); int number = console.nextInt(); while (number != -1) { sum = sum + number; System.out.print("Enter a number (-1 to quit): "); number = console.nextInt(); } System.out.println("The total is " + sum);
Forever loops Called "forever" loops because their header's boolean test is often changed to a trivial true. Can be used to write a loop whose test is in the middle. break statement: Immediately exits a loop. Example: int num = 0; while (true) { if (num == 5) { break; } System.out.println(num); num++; } System.out.println(“Forever is over!”);
Forever loop syntax while (true) { ; if ( ) { break; } ; }
The Random class Java has a class named Random whose objects generate pseudo-random numbers. – Class Random is found in the java.util package. import java.util.*;
In your eclipse Random r = new Random(); if (r.nextInt(10)%2 == 0) { System.out.println("random int " + r.nextInt(10) + " is even"); } else { System.out.println("random int " + r.nextInt(10) + " is odd"); } Hint: don’t forget to import java.util.*;
In your eclipse Random r = new Random(); if (r.nextInt(10)%2 == 0) { System.out.println("random int " + r.nextInt(10) + " is even"); } else { System.out.println("random int " + r.nextInt(10) + " is odd"); } nextInt generated a different random number with each call. Just like scanner.nextInt() reads a new int with every call. how do we fix this?
In your eclipse – correct solution Random r = new Random(); int randomInt = r.nextInt(10); if (randomInt %2 == 0) { System.out.println("random int " + randomInt + " is even"); } else { System.out.println("random int " + randomInt + " is odd"); }
Homework for chapter 5 HomeworkAssigned onDue on Read BJP 5.1 and write notes11/04/201411/05/2014 Practice It : SC 1, 2, 3, 411/04/201411/05/2014 Practice It : SC 6,711/04/201411/05/2014 Practice It : Ex 511/04/201411/05/2014