Ask Question
5 August, 08:01

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);

+1
Answers (1)
  1. 5 August, 08:12
    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 & 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