RU beehive logo ITEC dept promo banner
ITEC 120
2009spring
ibarland
nokie
jmdymacek

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs

lab10b
printing powers

  1. 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;
      }
    

  2. Write a second method printSmallPowers(), which prints a similar table, but instead of stopping after a certain number of rows, it continues as long as the result is less than 1,000,000. Your result should have about twenty rows, before the power would become bigger than 1,000,000. (Don't worry about the columns lining up for i≥10.)
  3. 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.


  4. If you finish the previous two exercises, modify all your methods so that they take in an integer b, and print powers of b rather than powers of 2. (That is, printSmallPowers(7) should print the powers of seven up to a million, and printKPowers(7,5) would print the first five powers of seven.)
  5. To try: If you change your original program to print powers of 2 up until two billion (instead of one million), what happens? Can you explain the program's behavior?

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.      

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs


©2009, Ian Barland, Radford University
Last modified 2009.Apr.15 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme