UVa CS

University of Virginia Computer Science

LNK2LRN™ 2007/08

AP Comp Sci A

October 30 to

November 9. 

Ch.5: Loop Control

Statements.

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:

  1. The for loop:

    for (initialization_expression; loop_condition; increment_expression){
      // statements
    }
    

    The control of the for loop appears in parentheses following the keyword

    for. It has three parts separated by semi-colons.

    The first part, the initialization_expression, is executed before execution

     of the loop starts. This is typically used to initialize a counter for the

    number of loop iterations – for example i = 0. With a loop controlled by

    a counter, you can count up or down using an integer or a floating point

    variable. Below is an example:

    public static void main(String[] args) {
      byte value = 1;
      for (int i=0; i<8 ; i++) {
        value *= 2;
        System.out.println("Value is now " + value);
      }
    }

    Execution of the loop continues as long as the condition you have stated

    in the second part, the loop_condition, is true. This expression is checked

    at the beginning of each loop iteration, and when it is false, execution

    continues with the statement following the loop block. A simple example

    of what the loop_condition expression might be is i<8, so the loop would

    continue in this case as long as the variable i has a value less than 8.

    The third part of the control information between the parentheses, the

    increment_expression, is usually used to increment the loop counter.

    This is executed at the end of each loop iteration. This could be i++,

    which would increment the loop counter, i, by one. Of course, you might

    want to increment the loop counter in steps other than 1. For instance,

    you might write i += 2 as the increment_expression to go in steps of 2,

    or even something more complicated such as i = 2*i+1.

     

  2. The while loop:

    while (expression) {
      // statements
    }
    

    This loop executes as long as the given logical expression between

    parentheses is true. When expression is false, execution continues with

    the statement following the loop block. The expression is tested at the

    beginning of the loop, so if it is initially false, the loop statement block

    will not be executed at all. An example of a while loop condition might

    be, yesNo=='Y' || yesNo=='y'. This expression would be true if the

    variable yesNo contained 'y' or 'Y', so yesNo might hold a character

    entered from the keyboard in this instance. Below is another example:

    public class WhileLoop {
      public static void main(String[] args) {
        int limit = 20;                     // Sum from 1 to this value
        int sum = 0;                        // Accumulate sum in this variable
        int i = 1;                          // Loop counter
        // Loop from 1 to the value of limit, adding 1 each cycle
        while(i <= limit) {
          sum += i++;                       // Add the current value of i to sum
        }
        System.out.println("sum = " + sum);
      }
    }

     

  3. The do while loop

    do {
      // statements
    } while (expression);
    

    This loop is similar to the while loop, except that the expression

    controlling the loop is tested at the end of the loop block. This means

    that the loop block is executed at least once, even if the expression is

    always false. Below is an example:

    public class DoWhileLoop {
      public static void main(String[] args) {
        int limit = 20;                     // Sum from 1 to this value
        int sum = 0;                        // Accumulate sum in this variable
        int i = 1;                          // Loop counter
        // Loop from 1 to the value of limit, adding 1 each cycle
        do {
          sum += i;                         // Add the current value of i to sum
          i++;
        } while(i <= limit);
        System.out.println("sum = " + sum);
      }
    }

  4. We can compare the logic of the three kinds of loops in a diagram.

5. Nested Loops

You 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 Statement

There 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 Statement

Where 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 Loop

We 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 Statement

Java 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.

 

 

 

 

Anti-Phishing Game.

 

 

animated open door gifARCHIVES:   CH.1   CH.2&3  CH.4

JAVA RESOURCES and WEBSITES TO VISIT:

Prime Numbers

Review of Java

Elements of Java

Honda ASIMO

MIT Artificial Intelligence

University of Virginia Oracle