Computer Science 1
Top Lectures Assignments Noticeboard

While loops

Repetition in programming

  1. Motivation
  2. Example of Java while statement

  3. Should be able to identify conditional part (continuing condition), and the loop body. If the continuing condition is true, the loop body is executed. After that is executed, the condition is checked again. If the continuing condition is false, the statement after the loop is executed.
    while (counter <= 1000) {                while (condition) {
      System.out.println (counter);            body
      counter += 1;
    }                                        }
    System.out.println ("Finished");
  4. Summing a list of numbers

  5. While statements are good when you don't know how many times the loop is going to be repeated, but you know the condition that will cause  you to stop. How do we know when there is no more input? How do we sum a list of numbers?
    initialize sum to 0
    while there are more numbers
      read the next number
      add it to the sum
    Things we now know:
    1. what a while statement looks like
    2. how to test for no more input
    3. how to read a number
    4. how to add it to another number
    BasicDataReader keyboard = new BasicDataReader ();
    int sum = 0;
    int inputNumber;
    while (!keyboard.eof ()) {
      inputNumber = keyboard.readInt ();
      sum += inputNumber;
    }
    Recall that !keyboard.eof() will be true if keyboard.eof() is false (i.e., the end of the file hasn't been reached)

    Running the program:

    Problems:
  6. Exercise

  7. Modify the above program to calculate the average of the numbers entered.
  8. Patterns

  9. Reading from a file and processing elements is a common task. We can use this type of loop in many cases:
    while (need to continue) {
      read next element
      process the element
    }
    All we need to know: Note that the text book describes another common loop pattern.
     
  10. Testing loops
  11. Example source code

Last modified: 10/20/1999