|
Study the following code:
class LoopTest begin function int powerOf2A(int n) begin var int counter = n; var int result = 1; while (counter != 0) begin result = 2 * result; counter = counter - 1; end return result; end function int powerOf2B(int n) begin var int counter = n; var int result = 1; do begin result = 2 * result; counter = counter - 1; end while (counter != 0); return result; end function int powerOf2C(int n) begin var int result = 1; for (var int counter = n; counter != 0; counter = counter - 1) begin result = 2 * result; end return result; end function int powerOf2D(int n) begin var int result = 1; superfor (var int counter = n downto 1) begin result = 2 * result; end return result; end /** * Prints a row of stars of a given length. */ function void printLineC(int length) begin for (var int i = 0; i<length; i=i+1) begin System.out.print("#"); end System.out.println(); end beginMain // For question 4.1 add some code here... endMain end
Question 4.2: To the main function add some code to call the functions powerOf2A, powerOf2B, powerOf2C and powerOf2D to verify that they all return the same result. To inspect the result you will need to apply the System.out.println() statement to the values returned by those functions.
Question 4.3: 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.
Question 4.4: By copying the pattern of powerOf2A, powerOf2B, powerOf2C and powerOf2D, write methods printLineA, printLineB and printLineD that work identically to the method printLineC, except that they use while loops, do loops and superfor loops, respectively. Add some code to the main function to test them out.
Question 4.5: 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?
Back to J.T.W |
This page has the following hit count:
|