Menu Close

Power of 2 in Java …fcukthecode.com

Write a program that takes a command-line argument n and prints a table of the powers of 2 that are less than or equal to 2^n.0 <= n < 31 if u declare as int.

Input:
Enter any number:  4

Output:
0 1
1 2
2 4
3 8
4 16
import java.io.*;
import java.util.*;
public class temp{
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Enter any number:  ");
    int a = in.nextInt();

    for (int i=0 ; i<=a; i++)
    {
     double f = Math.pow(2, i);
     System.out.println(i +" " + (int)f);
    }
  }
}

INPUT_1:
Enter any number:  5

OUTPUT:
0  1
1  2
2  4
3  8
4  16
5  32


INPUT_2:
Enter any number:  7

OUTPUT:
0  1
1  2
2  4
3  8
4  16
5  32
6  64
7  128


INPUT_3:
Enter any number:  10

OUTPUT:
0  1
1  2
2  4
3  8
4  16
5  32
6  64
7  128
8  256
9  512
10  1024


INPUT_4:
Enter any number:  4

OUTPUT:
0  1
1  2
2  4
3  8
4  16


INPUT_5:
Enter any number:  8

OUTPUT:
0  1
1  2
2  4
3  8
4  16
5  32
6  64
7  128
8  256


ILLUSTRATION

Executed using javac in terminal