Plans for the Week and Assignments: 1. TUESDAY(10/30): The three types of loops in Java (For, While, and Do-While). Program5_1 - Compound Interest. HW: Read pages 277-287 and answer ques. 1-7 on page 288. 2. WEDNESDAY(10/31): Continue with the three types of loops in Java (For, While, and Do-While). Program5_2 - Temperature Conversion. HW: Read pages 288-300 and answer ques. 1-10 on pages 300-01. 3. THURSDAY(11/01): Continue with the three types of loops in Java (For, While, and Do-While). Program5_3 - Process Test Scores. HW: Read pages 301-304 and answer ques. 1-4 on page 305. 4. FRIDAY(11/02): Continue with the three types of loops in Java (For, While, and Do-While). Program5_4 - Even-Odd Sums. HW: Read pages 306-308 and answer ques. 1-7 on pages 308-09. 5. MONDAY(11/05): Numerical Accuracy. Program5_5 - The Golden Ratio. HW: Read pages 310-13 and answer ques. 1-5 on page 313. 6. TUESDAY(11/06): The Break and Continue Statements. Program5_6 - Nuclear Decay. HW: Read pages 314-24 and answer ques. 1-6 on pages 324-25. 7. WEDNESDAY(11/07): The Break and Continue Statements, continued. Program5_7 - Numerical Analysis. HW: Read pages 325-27 and write Program5_8 - (Exercise #1 on page 317: the Four Function Calculator). 9. THURSDAY(11/08): Review of Chapter 5 - Loops in Java. HW: Complete Review Handout. 10. FRIDAY(11/09): TEST on Ch.5 - Loops in Java. HW: Go to web-site for notes on Ch.6 - Using the Java System Classes.
Very Important: If you have any questions or were absent from class, see me before school (8:00 - 8:30 AM), during Lunch, 7th hour, or after school. Best to send an email to rpersin@fau.edu.
Website Notes: Ch.5 - Loop Control Statements.Introduction: A loop allows you to execute a statement or block of code repeatedly. The need to repeat a block of code arises in almost every program. There are three kinds of loop statements you can use, so let's look at thesein general terms first:
5. Nested LoopsYou can nest loops of any kind one inside another to any depth. Let's look at an example where we can use nested loops. A factorial of an integer, n, is the product of all the integers from 1 to n. It is written as n!. It may seem a little strange if you haven't come across it before, but it can be a very useful value. For instance, n! is the number of ways you can arrange n different things in sequence, so a deck of cards can be arranged in 52! different sequences. Let's try calculating some factorial values.
public class Factorial {
public static void main(String[] args) { long limit = 20; // to calculate factorial of integers up to a limit long factorial = 1; // factorial will be calculated in this variable // Loop from 1 to the value of limit for (int i = 1; i <= limit; i++) { factorial = 1; // Initialize factorial for (int factor = 2; factor <= i; factor++) { factorial *= factor; } System.out.println(i + "!" + " is " + factorial); } } } 6. The continue StatementThere are situations where you may want to skip all or part of a loop iteration. Suppose we want to sum the values of the integers from 1 to some limit, except that we don't want to include integers that are multiples of three. We can do this using an if and a continue statement: for(int i = 1; i <= limit; i++) { if(i % 3 == 0) { continue; // Skip the rest of this iteration } sum += i; // Add the current value of i to sum } The continue statement is executed in this example when i is an exact multiple of 3, causing the rest of the current loop iteration to be skipped. Program execution continues with the next iteration if there is one, and if not, with the statement following the end of the loop block. The continue statement can appear anywhere within a block of loop statements. You may even have more than one continue in a loop. 7. The Labeled continue StatementWhere you have nested loops, there is a special form of the continue statement that enables you to stop executing the inner loop – not just the current iteration of the inner loop – and continue at the beginning of the next iteration of the outer loop that immediately encloses the current loop. This is called the labeled continue statement. To use the labeled continue statement, you need to identify the loop statement for the enclosing outer loop with a statement label. A statement label is simply an identifier that is used to reference a particular statement. When you need to reference a particular statement, you write the statement label at the beginning of the statement in question, and separated from the statement by a colon. Let's look at an example: We could add a labeled continue statement to omit the calculation of factorials of odd numbers greater than 10. This is not the best way to do this, but it does demonstrate how the labeled continue statement works: public class Factorial {
public static void main(String[] args) {
long limit = 20; // to calculate factorial of integers up to this value
long factorial = 1; // factorial will be calculated in this variable
// Loop from 1 to the value of limit
OuterLoop:
for(int i = 1; i <= limit; i++) {
factorial = 1; // Initialize factorial
for(int j = 2; j <= i; j++) {
if(i > 10 && i % 2 == 1) {
continue OuterLoop; // Transfer to the outer loop
}
factorial *= j;
}
System.out.println(i + "!" + " is " + factorial);
}
}
}
8. Using the break Statement in a LoopWe have seen how to use the break statement in a switch block. Its effect is to exit the switch block and continue execution with the first statement after the switch. You can also use the break statement to break out from a loop when you need. When break is executed within a loop, the loop ends immediately and execution continues with the first statement following the loop. To demonstrate this we will write a program to find prime numbers. In case you have forgotten, a prime number is an integer that is not exactly divisible by any number less than itself, other than 1 of course. public class Primes { public static void main(String[] args) { int nValues = 50; // The maximum value to be checked boolean isPrime = true; // Is true if we find a prime // Check all values from 2 to nValues for(int i = 2; i <= nValues; i++) { isPrime=true; // Assume the current i is prime // Try dividing by all integers from 2 to i-1 for(int j = 2; j < i; j++) { if(i % j == 0) { // This is true if j divides exactly isPrime = false; // If we got here, it was an exact division break; // so exit the loop } } // We can get here through the break, or through completing the loop if(isPrime) // So is it prime? System.out.println(i); // Yes, so output the value } } } } 9. The Labeled break StatementJava also makes a labeled break statement available to you. This enables you to jump immediately to the statement following the end of any enclosing statement block or loop that is identified by the label in the labeled break statement. This mechanism is illustrated in the following diagram: The labeled break enables you to break out to the statement following an enclosing block or loop that has a label regardless of how many levels there are. You might have several loops nested one within the other, and using the labeled break you could exit from the innermost loop (or indeed any of them) to the statement following the outermost loop. You just need to add a label to the beginning of the relevant block or loop that you want to break out of, and use that label in the break statement. ust to see it working we can alter the previous example to use a labeled break statement: public class FindPrimes { public static void main(String[] args) { int nPrimes = 50; // The maximum number of primes required // Check all values from 2 to nValues OuterLoop: for(int i = 2; ; i++) { // This loop runs forever // Try dividing by all integers from 2 to i-1 for(int j = 2; j < i; j++) { if(i % j == 0) { // This is true if j divides exactly continue OuterLoop; // so exit the loop } } // We only get here if we have a prime System.out.println(i); // so output the value if(--nPrimes == 0) { // Decrement the prime count break OuterLoop; // It is zero so we have them all } } // break OuterLoop goes to here } } The program works in exactly the same way as before. The labeled break ends the loop operation beginning with the label OuterLoop, and so effectively branches to the point indicated by the comment. Of course, in this instance its effect is no different from that of an unlabeled break. However, in general this would work wherever the labeled break statement was within OuterLoop. For instance, it could be nested inside another inner loop, and its effect would be just the same – control would be transferred to the statement following the end of OuterLoop.
|
|
|