97.7k views
2 votes
How many times does the following loop execute? double d; Random generator = new Random(); double x = generator.nextDouble() * 100; do { d = Math.sqrt(x) * Math.sqrt(x) - x; System.out.println(d); x = generator.nextDouble() * 10001; } while (d != 0); exactly once exactly twice can't be determined always infinite loop

User AsValeO
by
4.5k points

1 Answer

6 votes

Answer:

The number of execution can't always be determines

Step-by-step explanation:

The following points should be noted

Variable d relies on variable x (both of double data type) for its value

d is calculated as


d = √(x)^2 - x

Mere looking at the above expression, the value of d should be 0;

However, it doesn't work that way.

The variable x can assume two categories of values

  1. Small Floating Point Values
  2. Large Floating Point Values

The range of the above values depend on the system running the application;

When variable x assumes a small value,


d = √(x)^2 - x will definitely result in 0 and the loop will terminate immediately because
√(x)^2 = x

When variable x assumes a large value,


d = √(x)^2 - x will not result in 0 because their will be
√(x)^2 \\eq x

The reason for this that, the compiler will approximate the value of
√(x)^2 and this approximation will not be equal to
x

Hence, the loop will be executed again.

Since, the range of values variable x can assume can not be predetermined, then we can conclude that the number of times the loop will be executed can't be determined.

User Yashar Ahmadov
by
5.2k points