Ok, I have to write a code snippet that prints out the value of 2 to the powers of 1 – 31 in a 10 character width, right-justified column. You may not use any literals or Math methods.

Seeing as Im not allowed to use Math.pow, the only other option I can see is a for loop that counts from 1 to 31 and 32 if statements for each count does the correct multiplication of an integer at each count and finally prints out the integer.

int value = 0;

for (int counter = 0; counter < 32; counter++)
        {
                if (counter == 1)
                      value = 2 * counter;
                if (counter == 2)
                      value = 2 * counter;
                if (counter == 3)
                       value = 2 * 2 * 2;
                if (counter == 4)
                       value = 2 * 2 * 2 * 2;
                 
               System.out.print(value + " ");

Please advise if you see a better more efficient way of coding this that Im not seeing?

Recommended Answers

All 3 Replies

Maximum value is to stored with int type is 2147483647. So, you cannot use value of int type.

Tryout this code:

long value=1;
      for(int i=1;i<=31;i++)
       {
          value=value * 2;
          System.out.println(i +  " " + value);
       }

If the max value required is 2^31 this will fit in an int. 2^31+1 won't.

Thanks for the assist!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.