Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100?
```
A:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum = i / (i + 1);
}
System.out.println("Sum is " + sum);
B:
double sum = 0;
for (int i = 1; i < 99; i++) {
sum += i / (i + 1);
}
System.out.println("Sum is " + sum);
C:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum += 1.0 * i / (i + 1);
}
System.out.println("Sum is " + sum);
D:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum += i / (i + 1.0);
}
System.out.println("Sum is " + sum);
E:
double sum = 0;
for (int i = 1; i < 99; i++) {
sum += i / (i + 1.0);
}
System.out.println("Sum is " + sum);
```
a. BCD
b. ABCD
c. B
d. CDE
e. CD
e. CD
Note that 1 / 2 is 0.5 in a math expression. In Java, however, integer division yields an integer. The fraction part is truncated. Therefore, i / (i + 1) is 0. (A) and (B) are incorrect. (E) is incorrect because the last i in the loop is 98. So the last item 99 / 100.0 is not added to sum. So, the correct answer is CD.
You might also like to view...
What DSL variant has a distance limitation of 18,000 ft. between a DSL modem and its DSLAM?
a. HDSL b. ADSL c. SDSL d. VDSL
Why is the assumption of high mean nodal degree necessary to achieve a scale-free network with the scaling exponent as 1? Explain.
What will be an ideal response?