Next: Tutorial 5 A beer drinking song, Previous: Tutorial 3 superfor loops and for loops, Up: J.T.W. Tutorials [Contents][Index]
Question 4.4.1: Study, compile and run the following code:
classLoopTestbeginfunctionintpowerOf2A(intn)beginvarintcounter = n;varintresult = 1;while(counter > 0)beginresult = 2 * result; counter = counter - 1;endreturnresult;endfunctionintpowerOf2B(intn)beginvarintcounter = n;varintresult = 1;dobeginresult = 2 * result; counter = counter - 1;endwhile(counter > 0);returnresult;endfunctionintpowerOf2C(int n)beginvarintresult = 1;for(varintcounter = n; counter > 0; counter = counter - 1)beginresult = 2 * result;endreturnresult;endfunctionintpowerOf2D(int n)beginvarintresult = 1;superfor(varintcounter=ndownto1)beginresult = 2 * result;endreturnresult;end/** * Prints a row of stars of a given length. */functionvoid printLineC(int length)beginfor(varint i = 0; i<length; i=i+1)beginSystem.out.print("#");endSystem.out.println();endbeginMain// For Question 4.4.1 add some code here...endMainend
Question 4.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.4.3: There is a bug in the powerOf2B function
because it does not behave correctly in the case when n is zero or
less. Put an if (...) then ... statement at the top of this function
to make it handle the case of zero properly. Also make it return 1 in
the case that n is less than zero.
Question 4.4.4: There is a bug in the powerOf2D function
because it does not behave correctly in the case when n is zero or
negative. Make it return 1 if n <= 0. Put an if (...) then ...
statement at the top of this function to make it handle these cases
properly. Since this function returns an int, make it return 1 in
these cases.
Question 4.4.5: By copying the pattern of powerOf2A,
powerOf2B, powerOf2C and powerOf2D, write functions
printLineA, printLineB and printLineD that work
identically to the function 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.4.6: 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?
Next: Tutorial 5 A beer drinking song, Previous: Tutorial 3 superfor loops and for loops, Up: J.T.W. Tutorials [Contents][Index]