Processing to make 2 array in one

As others have stated you might simply want to try
concat();

however if the goal is to code the functionality yourself, the code you have provided is almost there.

Remember when coding break your task down.

You want to join two arrays, so the indecies of one array has to go into the other.

To access ONE array we use a for loop, this allows us to access ALL values in said array.

So if i

for (int i=0;i<array.length;i++){
  int k = array[i];
  
}

now this doesn’t do anything other than access the value.
We also know how to create and add values to arrays.

int[] array = new Array[5];

for (int i=0;i<array.length;i++){
  array[i] = random(200);
}

its really the same thing because the size of the array is not amended by the for loop and is instanced before it.

However this tells us that if we want to add to any array we only need one for loop providing that the data is only coming from one array

If however the data comes from two arrays, you will need to use a for loop twice, this doesn’t mean a nested for loop, it means run a for loop once to add values of the first array, then again for the second array.

int[] a = { 1, 2, 25 };
int[] b = { 9, 18 };
int [] arraynew = new int [a.length + b.length];

for (int i=0; i < a.length ; i++)
{
for( int j=0; j < b.length; j++)
{
arraynew[i] = a[i] + b[i];

println(arraynew[i]);

}
}

note you are making use of nested loops, which wont have the intended effect here. Also all that aside you aren’t using j to locate any of the values. Finally because

arraynew[i] = a[i] + b[i];

is linked to the for loop this will cause issues if the arrays arent the same size;

Anyways I think the answer has already been answered much better by others, however if you have to use for loops then, you have to consider the steps you have to go through.

Dan Shiffman’s videos on the topic are more than suited for this task and providing you watch them should help you.

4 Likes