Lab 8 In-Class: While Loops

This lab is designed to give you practice writing while loops. As usual, create a subdirectory for this lab, open up the Web version of this handout in Mozilla Firefox, and open emacs.

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

    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.

    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.

    2. Number each line in the output, and add a message at the end of the loop that says how many times the message was printed. So if the user enters 3, your program should print this:
        1 I love Computer Science!!
        2 I love Computer Science!!
        3 I love Computer Science!!
      Printed this message 3 times.  
      

    3. After the above works, add a second loop after the one that is there that does exactly the same thing (including the print statement after the loop) but initialize the loop control variable count to 0 instead of 1 and make the other adjustments necessary. Your program should now print the numbered message the given number of times twice (print a blank line in between!).

    4. Now add a third loop after the others 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 two loops):
        3 I love Computer Science!!
        2 I love Computer Science!!
        1 I love Computer Science!!
        The END!!!
      

    Print this program to turn in.

  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
      

    3. Modify the program so that it also finds the sum of the powers of 2. Remember that to sum values in a loop you need a variable to hold the sum. That variable should be initialized to 0 before the loop, then inside the loop it is updated to do the addition (in this case, you need to decide which variable you are adding to the sum and whether you should add before or after that variable is updated in the loop). Add a print statement after the loop to print out the sum.

    Print this program to turn in.

  3. 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.
    1. The file Factorial.java contains a skeleton of a program that will ask the user for a non-negative integer and compute and print the factorial of that integer. Open the file and complete it. You'll need a while loop to do most of the work -- this is a lot like computing the sum of the numbers from 1 to some limit, but it's a product instead. You need to declare two variables for your calculation (one to hold the product - what is the role of the other?), initialize them before the loop, then write the correct loop. Print the answer after the loop.

    2. Run your program to make sure it works. What do you get when you enter 0? If the program doesn't get 1 then modify the loop control (and perhaps your initializations) so that it does get 1 when the user enters 0 (you should not need to add any ifs to get the program to correctly compute 0!). Make sure the program still works for integers greater than 0 (be sure to test 1 and another integer).

    3. Now modify your 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: you will need another while loop before the loop that computes the factorial. You should not need to change any of the code that computes the factorial.

    4. As we discussed in class, when a value is too big (in the positive or negative direction) to fit in the number of bits available, overflow occurs. Factorials get big very fast, so they are a good place to see overflow. Do the following:
      1. The loop that computes n! is actually computing the factorial of each number from 1 to n-1 along the way. Add statements to your loop to print the current value of the integer and its factorial in each loop iteration. So if the user entered 4, your program should now print
        1!=1
        2!=2
        3!=6
        4!=24
        
        Print your revised program and write the answer to the following question on it.

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

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

    Print this program to turn in.

  5. Election Day Next week is election day and, as you know, people are concerned about the accurate counting of votes. In this exercise you will write a simple program to help tally election results. The program will assume that there are only two candidates in the election. It will take as input the number of votes each candidate receives in each voting precinct and find the total number of votes for each candidate and the number of precincts each candidate carries (wins). Clearly a loop is needed. Each iteration of the loop is responsible for reading in the votes from a single precinct and updating the tallies.

    Candidates for the election will be represented by a Candidate class. A candidate will be described by the following instance data:

    The class contains the following methods:

    A skeleton of the Candidate class is in the file Candidate.java. Open the file and complete the class as indicated in the comments. Compile the class to make sure you have no syntax errors.

    The file Election.java contains a skeleton of the program to tally the election results. Open the file and do the following as indicated by the starred comments in the program:

    1. Note that code to read in each candidate's name and party is already there. Add code to declare and instantiate the two Candidate objects.
    2. Set the precinct counter numPrecincts to 0 before the loop (this is part of the loop setup).

    3. Add code to control the loop. The loop should be controlled by asking the user whether or not there are more precincts to report (that is, more precincts whose votes need to be added in). The user should respond by typing in the letter y or n (upper or lowercase). To control the loop by asking the user you need to do three things:
      1. The variable response (type String - already declared) should be initialized before the loop. In this case just set it to "Y" so the loop control condition will be true.
      2. The loop control condition must be put in the while statement. The loop should execute as long as the response is y or Y - you can avoid using an or by using the equalsIgnoreCase method in the String class (see page 119).
      3. Just before the end of the body of the loop (see the comment) add a prompt to ask the user if there is another precinct. Read in the response. NOTE: You will need to use a scan.nextLine() statement twice - the first one reads in the NEW LINE character that remains in the input stream after reading the last integer the second one actually reads in the user's response.

    4. Complete the code inside the loop as directed by the comments. In most cases you will need to invoke methods in the Candidate class. Be sure that when you check to see who won the precinct you account for ties.

    5. Print out the results after the loop. This should include the name, party, total votes and the number of precincts won for each candidate. Also compute and print out the number of ties.

What to Hand In