Consider the following code segment. The code is intended to read nonnegative numbers and compute their product until a negative
number is read. However it does not work as intended. Assume that the readInt method correctly reads the next number from the input stream.int k = 0;int prod = 1;while (k>=0){System.out.println("Enter a number: ");k= readInt( );prod = prod*k;}System.out.println("product: "+prod);
Which of the following best describes the error in the program?
A. The variable prod is incorrectly initialized
B. The while condition always evaluates to false
C. The while condition always evaluates to true
D. The negative number entered to signal no more input is included in the product
E. If the user enters a zero, the computation of the product will be terminated prematurely
Option D The negative number entered to signal no more input is included in the product
Explanation:
Given the code as follows:
int k = 0;
int prod = 1;
while (k>=0)
{
System.out.println("Enter a number: ");
k= readInt( );
prod = prod*k;
}
System.out.println("product: "+prod);
The line 7 is a logical error. Based on the while condition in Line 3, the loop shall be terminated if k smaller than zero (negative value). So negative value is a sentinel value of this while loop. However, if user enter the negative number to k, the sentinel value itself will be multiplied with prod in next line (Line 7) which result inaccurate prod value.