Sofia.canella Sofia.canella - 1 year ago 68
Java Question

Creating a program that increments Arrays

An integer array stores values 3,2,3,4,5. i am trying to create a program that increments these values by 2 and then saves the result into the same array using a for loop. i tried but something is wrong with my code, here:

public class ArrayClass {
int a[] = {2, 3, 3, 4, 5};

public class ArrayObject {
public static void main(String[] Ella) {
int a[] = new int[5];
int i;
for (i = 2; i < a.length; i = i + 2) {
a[i] = i + 2;

Answer Source

The error is that when you do i = i + 2, you are just incrementing the position index, not the actual value in that position.

you need to do:

a[i] = a[i]+2;

Let me explain what a[i] is:

 1 2 3 4 5

The first row are the values. The second row is the index. "Index" means the position number of each of positions in the array.

Another problem is that, when you initialise i, it need to be i=0. That is because i array indices (plural of index) always start from 0. That means that a[0] is the first position in the array That would be number 3 from your data set.