0

I have two arrays and I am trying to assign the values of one array, i.e. arrayOne[0] should be equal to the corresponding index in arrayTwo[0]. I am trying to do this using a forloop so that it loops through the the index of one array assigning the values sequentially. so far I have: for (int a =0; a< arrayOne.length; ++) { // this sets the an int that loops through the value of the arrays(both arrayOne and arrayTwo are the same length) I am lost however after this how to create the for loop which assigns index 0 = 0 and then incrementally step through this.

I know this is a very basic question but I am, as my name suggests, struggling to learn coding.

1 Answers1

2

I am lost however after this how to create the for loop which assigns index 0 = 0 and then incrementally step through this.

There are many ways to copy arrays. But since you specifically asked for a for loop solution, just create a new array of the same size and use a for loop as shown to index them.

int [] a = {1,2,3,4,5,6,7};
int [] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
     b[i] = a[i]; // this copies element a[i] to b[i] where i is the index.
}

System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));

Prints

[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
WJS
  • 36,363
  • 4
  • 24
  • 39