LoopTest.java Answers

Click here to go back to the questions
// ANSWERS:
//
// (1) In the doStuff method, some lines of code to test out
// the methods powerOf2A, powerOf2B and powerOf2C.
// 

// The following should each produce the output of 16:
System.out.println(powerOf2A(4));
System.out.println(powerOf2B(4));
System.out.println(powerOf2C(4));

// 
// (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.
// 

public int powerOf2B(int n) {
   if (n == 0) return 1;
   int counter = n;
   int result  = 1;
   do
   {
      result = 2 * result;
      counter--;
   } while (counter != 0);
   return result;
}

// 
// (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.
// 

public void printLineA(int length)
{
   int i=0;
   while (i < length)
   {
      System.out.print("#");
      i++;
   }
   System.out.println();
}
public void printLineB(int length)
{
   if (length == 0) return;
   int i=0;
   do
   {
      System.out.print("#");
      i++;
   } while (i < length);
   System.out.println();
}

// The following should each produce the output of "####":
System.out.println(printLineA(4));
System.out.println(printLineB(4));
System.out.println(printLineC(4));


// 
// (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?
// 

// ANSWER: It depends on what the construct is going to be
// used for.

//