Lab 7 In-Class: While Loops

As usual, create a subdirectory for this lab, open up the Web version of this handout in Mozilla Firefox, and open Eclipse.

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. In Eclipse, there is a red square on the console window that you click to stop the program.

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. 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. 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. 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 starting at 1 and ending at the limit) 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.

  4. 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 print (after the other printing from the other loop) 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. 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:
      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. 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. 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. 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 adds up the points scored in a specified number of games (the number is input to the program) and finds the average number of points scored per game. The basic program will contain a count-controlled loop that reads in scores and adds them up.

  1. The file GameStats.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 games to make sure it works.

  2. 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
    
    Suppose a valid score in this game (whatever it is!) is in the range 0 - 250. 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 score. 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 points scored in game " + gameCount):
                score = scan.nextInt();
    
                // Validate the score
                while ( ... score is not valid ... )
                  { 
                     Tell the user the score is not correct
                     Ask the user to enter a score in the correct range
                     Read in the new score
                  }
    
                // Process the score - from here on out the code is what
                // you already have
    

    Test your program thoroughly. Make sure it catches all types of incorrect input.

  3. Finally change the loop control condition (the main loop, not the validation loop) so that the loop stops either when a perfect score is obtained (a score of 250) or the specified number of games has been reached. After the loop add a statement that prints a congratulations message if the loop ended because of a perfect score. Your program should still print the average score for the games entered (so, for example, if the user says there will be 10 scores but the scores entered are 100, 80, 148, 250 the program stops on the 250, prints the congratulations and the average score of 144.5). Test your program thoroughly.

  4. Print your completed program 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. Using the comments as a guide, complete the program so that it plays the game as described above.
  2. 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. 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. 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 to turn in.

What to Hand In