What is the result when the following code is run? double x = 1; double y = 1; int i = 0; do { y = x / 2; x = x + y; i = i + 1; } while (x < 2.5); System.out.print(i + " ");

Respuesta :

Answer:

The answer is: 3

Step-by-step explanation:

1. At the begining of the program we start by declairing the variables:

 double x=1, double y=1 and int i=0.

2. The structure do...while is used to defined the loop. x<2.5 is the finalization condition of the loop. i is the counter of the loop.

y=x/2 is the first calculation

x=x+y is the second one. Here is where the values of the variable x changes.

a) for the first iteration, the values of y and x are shown below:

[tex]\\\\x=1\\y=1\\y=1/2=0.5\\x=1+0.5=1.5\\i=1[/tex]

The variable x is minor to 2.5 so the loop will continue computing.

b)   the second iteration, the values of y and x are shown below::

 [tex]y=0.5\\x=1.5\\y=\frac{1.5}{2}=0.75\\ x=1.5+0.75=2.25\\i=2[/tex]

The variable x is still minor to 2.5 so the loop will continue computing.

c) third iteration:

[tex]y=0.75\\x=2.25\\y=\frac{2.25}{2} =1.1125\\x=2.25+1.125=3.375\\i=3[/tex]

The condition x<2.5 is not true so the loop ends.

3. System.out.print(i + " "); displays the value of the variable i wich value is 3.

Therefore the number 3 is display.