Lab 7 In-Class: While Loops

In this lab you will work in pairs. Here are the rules:

As usual, create a subdirectory for this lab (in one of the team member's directory), open up the Web version of this handout in Mozilla Firefox, and open Emacs.

Exercise #1: 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. (A) Fix the loop so it will execute exactly the number of times specified by the limit. Do not change any of the current code - just add the update of the loop control variable in the correct place. For example, if the user enters 3, your program should print this:
      Counter before the loop begins: 1
    
      Loop ...
      1 I love Computer Science!!
      2 I love Computer Science!!
      3 I love Computer Science!!
    
      Counter after the loop ends: 4
    

  2. (A) One problem students often have with loops (and with if statements) is adding semicolons where they don't belong. Add one at the end of the condition in the while statement above - so your while now looks like:
          while (count <= limit);
            {
              ...
            }
    
    
    Run the program and see what happens. Why did the program do what it did?

    Remove the semicolon before proceeding!!

  3. (A) Count controlled loops usually start the variable that counts at either 0 or 1. In most cases it doesn't matter which way you start but the code for the two ways is slightly different. Note that the current code starts the loop control variable count at 1. Modify the code so it prints the same numbered list (with numbering in the list starting at 1 and ending at the limit - the counter before and after will be different) but initialize the loop control variable count to 0 instead of 1 and make the other adjustments necessary. To make changes think about the order in which the statements inside the loop are executed - do not change the statement that prints the message. Run the program and make sure it prints the numbered message correctly (the counters may be different before and after the loop).

  4. (B) Now add a second loop after the other that again prints the "I love Computer Science" message the given number of times but this time count down. So if the user wants to print the message three times the program would first print the list 3 times as above then print again as shown below. Again, do not change the code in the print statement; instead change the variable that counts so it counts down. (HINT: Copy the code for the first loop, including the initializations and print statements both before and after the loop, then paste it after the current code and make the appropriate modifications.)
      Counter before the loop begins:  ______  
    
      Loop ...  
      3 I love Computer Science!!
      2 I love Computer Science!!
      1 I love Computer Science!!
    
      Counter after the loop ends:  _____
    

  5. (A) Finally, add a third loop that counts by 2 from 2 up to the limit. As before leave the print statement in the loop alone; make the count variable do all the work. If the user enters 8 for the limit, your program should print the following (beginning and ending values of the counter may vary but the loop should print as follows):
      Counter before the loop begins: _______
    
      Loop ...
      2 I love Computer Science!!
      4 I love Computer Science!!
      6 I love Computer Science!!
      8 I love Computer Science!!
    
      Counter after the loop ends: ______
    

  6. Be sure your program is properly formatted (CTRL-X, CTRL-P to select the whole program then CTRL-ALT-\).

  7. Print this program to turn in (be sure your name is typed in the program before you print!).

Exercise #2: Powers of 2

File PowersOf2.java contains a skeleton of a program to read in an integer from the user and print out that many powers of 2, starting with 20.

  1. (B) Using the comments as a guide, complete the program so that it prints out the number of powers of 2 that the user requests. Do not use Math.pow to compute the powers of 2! Instead, compute each power from the previous one (how do you get 2n from 2n-1?). For example, if the user enters 4, your program should print this:
    Here are the first 4 powers of 2:
    1
    2
    4
    8
    
  2. (B) Modify the program so that instead of just printing the powers, you print which power each is, e.g.:
    Here are the first 4 powers of 2:
    2^0 = 1
    2^1 = 2
    2^2 = 4
    2^3 = 8
    

Print this program to turn in.

Exercise #3: Summing in a Loop

As we have seen in class one task a loop often performs is adding up some values. In this exercise you will complete a program that computes baseball batting statistics by adding up the results of a specified number of times at bat. The basic program will contain a count-controlled loop that reads in the base the batter was able to get to at each time at bat (1 for first, 2 for second, 3 for third, 4 for home, 0 for a walk or out). The program counts the number of each type of hit then uses that to calculate the total number of hits, the batting average, and the slugging percentage.

  1. (A)The file BattingStats.java contains a skeleton of the program. Download the file, open it and observe that it already has declared the variables you need to make the loop do its job:

    Complete the program using the comments as a guide. Run the program several times with different numbers of at bats (including 0 at bats) to make sure it works.

  2. (B) Using a loop to verify input Often a loop is used in an interactive program to force the user to enter valid input - when the user enters an invalid input value the loop keeps asking for and reading in a new value until something correct is entered. The general structure of the loop is as follow:
           ...  
    
           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
    
    Valid input for this program is a 0, 1, 2, 3, or 4. Add a validation loop inside the current loop (a loop inside a loop is called a nested loop) to guarantee that the user enters a valid at bat result. The structure of your program will be as follows (you must translate it into correct Java!):
           while ( ....... ) {    // this is your current while statement
                ...
    
                System.out.print ("Enter the base hit at bat number " + atBatCount + ": ");
                baseHit = scan.next();
    
                // Validate baseHit - this is your new loop
                while ( ... input is not valid ... ) {
                    Let the user know the input is not valid
                    Ask them to try again
                    Read in the new value
                }
    
                // Process the input - from here on out the code is what
                // you already have 
    
           }
    

    Test your program thoroughly. Make sure it catches all types of incorrect numeric input (it won't catch the user entering a letter instead of a number so don't worry about that).

  3. (B) Finally change the loop control condition (the main loop, not the validation loop) so that the loop stops either when a batter hits a home run or the specified number of at bats has been reached. After the loop add a statement that prints a congratulations message if the loop ended because of a home run. Your program should still print the statistics for the at bats entered (so, for example, if the user says there will be 10 at bats but the results entered are 1, 1, 0, 4 the program stops on the 4, prints the congratulations and the number of hits as 3, the batting average as 0.75, and the slugging percentage as 1.5). Test your program thoroughly.

  4. Print your completed program (correctly formatted) to turn in.

Exercise #4: 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.

  1. (A) Using the comments as a guide, complete the program so that it plays the game as described above.
  2. (A) Modify the program so that if the guess is wrong, the program says whether it is too high or too low. You will need an if statement (inside your loop) to do this.
  3. (B) Now add code to count how many guesses it takes the user to get the number, and print this number at the end with the congratulatory message.
  4. (B) Finally, count how many of the guesses are too high, and how many are too low; print these values, along with the total number of guesses, when the user finally gets it.
  5. Print this program (correctly formatted) to turn in.

What to Hand In