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 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.

Computer Science & Information Technology

You might also like to view...

Using two keys in combination to perform an action is known as a(n) ________

A) quick method B) quick key C) keyboard cheat D) keyboard shortcut

Computer Science & Information Technology

The Primary key must be the first field in each record

Indicate whether the statement is true or false

Computer Science & Information Technology