As usual, create a subdirectory for this lab, open up the Web version of this handout in Mozilla Firefox, and open emacs.
This lab is designed to teach you the basics of writing while loops. A while loop is an example of a repetition statement (also called a loop) which allows a sequence of statements to be executed multiple times. The number of times the execution is repeated depends on a boolean condition. The basic syntax of a while statement is as follows:
         ...
	 while (  boolean expression  )
	 {
	     ... the statements to be repeated - the body of the loop
	 }
	 ...
As with an if statement when execution reaches the while statement,
the boolean expression is evaluated. If it is true all statements in
the body of the loop are then executed. After the body has been executed
the boolean condition is evaluated again.  If it is true the body
is executed again.  This is repeated until the boolean expression is
false at the time it is evaluated. 
The following is a basic loop that prints the
numbers from 1 to LIMIT and finds their sum:
   final int LIMIT = 100;         // setup
   int count = 1;                 // - initialize the loop control variable 
   int sum = 0;                   // - and the summing variable
   while (count <= LIMIT)         // condition
   {                              // body
     System.out.println(count);   //   -- perform task
     sum = sum + count;           //      (print and sum)
     count = count + 1;           //   -- update condition
   }
   System.out.println ("The sum of the integers from 1 to " +
        LIMIT + " is " + sum);
There are three parts to a loop:
Exercise #1: Summing in a Loop One task that often takes place in a loop is adding up some values. In the example above, the variable sum is keeping a running total of the integers 1, 2, 3, ... up to the limit. Note the key elements in getting this task done:
In this exercise we will take a count-controlled loop that prints out vacation days (the exercise we didn't have time for in last week's lab) and add code so it will read in the amount of money spent each day and find the sum. The main part of the program containing this loop is as follows (with blanks we will fill in to add the summing):
     int numDays;                 //total number of days of vacation
     int dayCount;                //counter for the vacation days
     ___________________________; //total amount spent on vacation
 
     ___________________________; //one day's expenditure
     
     System.out.println ("Vacation Days!!!");
     System.out.print ("How many days is your vacation? ");
     numDays = scan.nextInt();
     // Initialize the day counter and the total spent
     dayCount = 0;
     ____________________________________________________;
     // Count-controlled loop - executes numDays times
     while (dayCount < numDays) 
     {
        // Update the counter variable and print a message
        dayCount++;
        System.out.println ("Having fun on day " + dayCount + "!");
        // Get the amount spent this day
        System.out.print ("How much did you spend today? ");
        ______________________________________________________;
        // Update the total spent
        ______________________________________________________;
     }
     // After the loop - print a message and the total spent
     System.out.println ("Out of the loop - vacation over!");
     ___________________________________________________________;
Observe that unlike the earlier example the counter
variable starts at 0. It is standard to start counters either at
0 or 1 - which you choose makes some difference in the order of
statements in the body of the loop (you'll see this in exercise 3).
We want to add code above so the program will determine the total amount of money spent on vacation. That requires the following (fill in the blanks to do each step):
The file VacationDays.java has basically the same loop as above with some extra comments and prompts to read in the date that vacation starts. Do the following.
       cp ../lab7/Date.java  .
(Be sure you understand each part of this command!)
Exercise #2: A loop that isn't count-controlled Not all loops are count-controlled. Often there is some other condition, rather than a counter having reached some limit, that determines how many times a loop executes. For example, suppose that instead of knowing how many days a vacation is (and computing how much money is spent in those days) we instead know how much money we have to spend and want to stay on vacation until we reach or exceed that limit. Just a few changes to the above program can answer the new question. The basic outline is as follows:
     int dayCount;               // counter for the vacation days
     double spendingLimit;       // amount of money available to spend
     double totalSpent;          // total amount spent so far
     double daysExpenditure;     // one day's expenditure
     
     System.out.println ("Vacation Days!!!");
     System.out.print ("What is your spending limit? ");
     spendingLimit = scan.nextDouble();
     // Initialize the loop count and the total spent
     dayCount = 0;
     totalSpent = 0;
     
     // Loop continues until the total spent reaches the limit
     while ( _____________________________________________________ ) 
     {
          // everything in here is exactly the same as before
     }
     // After the loop - print a message
     System.out.println ("Out of the loop - vacation over!");
     ___________________________________________________________;
To modify the program to answer the "how many days until I reach my
spending limit?" question you need to fill in the two blanks (of course
the program needed to change the original question asked from how
many days to how much money):
Now do the following:
Exercise #3: Infinite Loops and Loop Counters
Breaking out of infinite loops: One of the first things you need to learn about loops is how to break out of infinite loops! Different systems have different keys for doing this. In Linux, CTRL-C stops a program that is running.
The program in LoveCS.java should print "I love Computer Science!!" as many times as the user wishes. Copy it to your directory and compile and run it to see how it works.
Clearly the program has a problem and it is a typical one when writing loops - there is no update of the loop control variable. Modify the program as follows:
1 I love Computer Science!! 2 I love Computer Science!! 3 I love Computer Science!! Printed this message 3 times.
3 I love Computer Science!! 2 I love Computer Science!! 1 I love Computer Science!! The END!!!Again, this change should come by changing the operation of the loop, not the print statement.
Exercise #4: Computing Products in a Loop
The factorial of n (written n!) is the product of the integers between 1 and n. Thus 4! = 1*2*3*4 = 24. By definition, 0! = 1. Factorial is not defined for negative numbers.
       ...  Prompt for and read in the input
       while ( ... the input is not valid ...)
       {
            Let the user know the input is not valid
            Ask them to try again
            Read in the new value
       }
       ... continue the program - now the input is guaranteed to be valid
Now modify your factorial program so that it checks to see if the user entered a negative number. If so, the program should print a message saying that a nonnegative number is required and ask the user to enter another number. The program should keep doing this until the user enters a nonnegative number, after which it should compute the factorial of that number. Hint: Add another while loop before the loop that computes the factorial. You should not need to change any of the code that computes the factorial.
1!=1 2!=2 3!=6 4!=24Add comments to your code to Answer the following question
int is represented with 32 bits using two's
complement.  The largest value that can be stored in an int
is 231 - 1 which is 2,147,483,647.
Run your program with an input of 20 and look at the values that
are printed.  At some point the factorial becomes negative, which is 
clearly wrong, but overflow actually occurs before this -- what is the
highest integer for which your program computes factorial correctly,
and what is its factorial?
Does this make sense given the largest possible int?  Explain.
Exercise #5: A Guessing Game
File Guess.java contains a skeleton for a program to play a guessing game with the user. The program should randomly generate an integer between 1 and 10, then ask the user to try to guess the number. As long as the user guesses incorrectly, the program should ask him or her to try again; when the guess is correct, the program should print a congratulatory message.
      Coin 1 beat Coin 2 getting to 10 heads. It took 23 flips.
      Coin 2 had 7 heads.
OR
      Coin 1 and Coin 2 tied - they reached 10 heads in 19 flips.