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.

Computer Science & Information Technology

You might also like to view...

You are passing a two dimensional array, defined as below, to a function. What would be a correct function prototype? (ROWS and COLS are global constants.)

int table [ROWS] [COLS]; a) float calculate (int matrix [ ] [ COLS], int rows); b) float calculate (int matrix [ROWS ] [ ], int rows); c) float calculate (matrix [ ROWS] [ COLS], int rows); d) float calculate (int matrix [ROWS ] [ ], int cols);

Computer Science & Information Technology

A sound-only Flash movie is generally created with ____.

A. a white background color B. a black background color C. a transparent background color D. the same background color as the page

Computer Science & Information Technology

The Form Header section and the Form Footer section must be added in Design view

Indicate whether the statement is true or false

Computer Science & Information Technology

Which of the following is NOT a benefit of avoiding redundancy in a database?

A) Reduces errors when recording new data B) User doesn't have to remember where data is stored C) Conserves space D) Prevents unauthorized manipulation of data

Computer Science & Information Technology