What does the following code do Be specific int x 1 int n S

What does the following code do? Be specific......

int x = 1;

int n;

String response;

response = JOptionPane.showInputDialog( null, \"Please enter an integer\");

n = Integer.parseInt( response);

int i = 1;

while ( i <= n )

{

    x = x * 2;

    i = i + 1;

}

system.out.println( x );

Solution

       int x = 1;
       int n;
       String response;
       response = JOptionPane.showInputDialog(null, \"Please enter an integer\");
       n = Integer.parseInt(response);

       int i = 1;
       while (i <= n) {
           x = x * 2;
           i = i + 1;
          
       }

       System.out.println(x);
Note: The above code calculates the 2 to the power of n
if n is 5 then x = x * 2 executes

x-->1*2-->2, increment i by 1 then n=5, i=2, x=2 if i<=n
x-->2*2-->4, increment i by 1 then n=5, i=3, x=4 if i<=n
x-->4*2-->8, increment i by 1 then n=5, i=4, x=8 if i<=n
x-->8*2-->16, increment i by 1 then n=5, i=5, x=16 if i<=n
x-->16*2-->32, increment i by 1 then n=5, i=6, x=32 if i<=n becomes false loop breaks

What does the following code do? Be specific...... int x = 1; int n; String response; response = JOptionPane.showInputDialog( null, \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site