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