0

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?

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by brandongood
0

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);
       }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.