what is wrong with each of the following code segments a int
what is wrong with each of the following code segments?
a. int[] values = new int[10];
for (int i = 1; i <= 10; i++)
{
values[i] = i * i;
}
b. int[] values;
for (int i = 0; i< values.length; i++)
{
values[i] = i * i;
}
Solution
a. int[] values = new int[10];
for (int i = 1; i <= 10; i++)
{
values[i] = i * i;
}
For above code since you have allocated 10 elements memory elements will start at indexing 0 not 1 so you will be accessing value[10] with above code which is invalid.
int[] values;
for (int i = 0; i< values.length; i++)
{
values[i] = i * i;
}
With the above code the problem is you havent initialize the the variable value. Due to which when you will access it you will get the error saying please initialize value variable.
![what is wrong with each of the following code segments? a. int[] values = new int[10]; for (int i = 1; i <= 10; i++) { values[i] = i * i; } b. int[] values; what is wrong with each of the following code segments? a. int[] values = new int[10]; for (int i = 1; i <= 10; i++) { values[i] = i * i; } b. int[] values;](/WebImages/1/what-is-wrong-with-each-of-the-following-code-segments-a-int-967751-1761495345-0.webp)