Ask Question
29 September, 11:38

What is the result of the following code? double[] values = new double[4]; double sum = 0.0; for (int i = 1; i < = 4; i++) { sum + = values[i]; }System. out. println (sum);

+5
Answers (1)
  1. 29 September, 13:00
    0
    The following code as it is results in an array out of bound exception.

    Explanation:

    The reason for this exception is that you tried to access index 4 for an array of length four, because Arrays are indexed from zero, the last element in an array of length 4, will be at index 3 (i. e. 0,1,2,3)

    To fix this change for (int i = 1; i < = 4; i++) to for (int i = 0; i < 4; i++).

    In this way you code compiles and returns the sum of all elements in the array. Since this array is only created and empty, it outputs 0.0
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “What is the result of the following code? double[] values = new double[4]; double sum = 0.0; for (int i = 1; i < = 4; i++) { sum + = ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers