Ask Question

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

+5
Answers (1)
  1. 11 September, 20:17
    0
    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.

    The correct code should be

    int k = 0; int prod = 1; while (k>=0) { prod = prod*k; System. out. println ("Enter a number: "); k = readInt (); } System. out. println ("product: "+prod);
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Consider the following code segment. The code is intended to read nonnegative numbers and compute their product until a negative number is ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers