|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
Write a method printKPowers(int k) which System.out.printlns the powers of 2, from 20 to 2k in the following format:
i 2^i - --- 0 1 1 2 2 4 3 8 4 16 …etc. |
To be checked off, you should call1 the method we walked through at the start of yesterday's lecture. However, you should not change this method, nor should you have any multiplication in your program (besides the “answerSoFar*2” included below).
int powerOf2( int n ) { int i = 0; int answerSoFar = 1; while (i<n) { answerSoFar = answerSoFar * 2; i = i + 1; } return answerSoFar; } |
We will check off through #2. Note that these two exercises are reminiscent of lecture's growTilBig and printHolidayMessage, although you'll be calling methods in the condition/loop-body.
1 You might notice that the computer is doing some work over and over, and if we were clever and blended powerOf2 with printSmallPowers we could optimize this. True, but for now we will work on getting a working prototype. Only if this simple code actually runs too slowly, should we worry about trying to optimize it. ↩
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Apr.15 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |