+ 1
why it gives me error?
public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=1; x<=myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } }
5 odpowiedzi
+ 3
Because you are trying to access invalid element
arrays first element is 0
exp:
int[] arr={1,2,3};//length =3;
arr[0]=1;
arr[1]=2;
arr[2]=3;
correct like this
...
for(int x=0;x<arr.lenght;x++)
...
+ 1
your problem is with sum += myArr
try changing it
0
I did it wrong because I didn't look at the index. ty😁
0
look at your code in
for(int x=1; x<=myArr.length; x++)
the index of array start from 0 so you have to make for like this
for(int x=0; x<=myArr.length; x++)
now here is an other problem the array end with index (arraylength-1)
so you
here in code when x= myArr.length
will access
myArr[x]
which means
myArr[myArr.length ]
which does not exist
so you have to make the code like this
for(int x=0; x<myArr.length; x++)
or like this
for(int x=0; x<=myArr.length-1; x++)
0
hi