LoopTest.java Questions

Instructions

  1. With the left mouse button pressed, drag the mouse across the contents of the program listing that is shown below. This will select the program listing. Then choose Copy from the Edit menu of your web browser to copy the program listing to the clipboard.
  2. Start your text editor and create a new file called LoopTest.java. Choose Paste to paste the contents of the program listing from the clipboard into the new file.
  3. Save the file to disk and begin answering the questions that are shown below.
  4. When you need to look at the model answer, click here.
  5. Click here to go back to the tutorials menu.

Program listing

// LoopTest.java
// Copyright (C) 1998-2016 Davin Pearson
// Website: http://davin.50webs.com/java-tutorials

class LoopTest {
   // The main method is the point of entry into the program...
   public static void main(String[] args)
   {
      LoopTest me = new LoopTest();
      me.doStuff();
   }
   // add your code here...
   public void doStuff()
   {

   }
   // These functions compute powers of two.
   public int powerOf2A(int n)
   {
      int counter = n;
      int result  = 1;
      while (counter != 0)
      {
         result = 2 * result;
         counter--;
      }
      return result;
   }
   public int powerOf2B(int n)
   {
      int counter = n;
      int result  = 1;
      do
      {
         result = 2 * result;
         counter--;
      } while (counter != 0);
      return result;
   }
   public int powerOf2C(int n)
   {
      int counter;
      int result;
      for (counter = n, result = 1; counter != 0; counter--)
      {
         result = 2 * result;
      }
      return result;
   }
   /**
     *  Prints a row of stars of a given length.
     */
   public void printLineC(int length)
   {
      for (int i=0; i<length; i++)
      {
         System.out.print("#");
      }
      System.out.println();
   }
}

// QUESTIONS:
//
// (1) In the doStuff method, some lines of code to test out
// the methods powerOf2A, powerOf2B and powerOf2C.
// 
// (2) There is a bug in the powerOf2B method because it
// does not behave correctly in the case when n is zero.
// Put an "if" statement at the top of this method to make
// it handle the case of zero properly.
// 
// (3) By copying the pattern of powerOf2A, powerOf2B and
// powerOf2C, write methods printLineA and printLineB that
// work identically to the method printLineC, except that
// they use "while" loops and "do" loops.  Add some code to
// the doStuff method to test them out.
// 
// (4) Based on the previous three questions, is there a best
// looping construct?  Or does it depend on what the looping
// construct is going to be used for?
//