Help rewriting a 2d array

I need to split up a 2D array into a smaller 2D array, where every other column is rewritten to a new array.
so .. Originalarray[20][40] into Newarray[20][20].
Im having trouble doing this
So far I have
Where Newdata[][] is the original array and pHB[][] is the new smaller array. This prints the correct columns correctly but prints them twice each
[
double pHB[20][20]; //creates new 2D array
for (int i = 0; i <20; i++) //nested for loops to read data into 2d array
{
for (int j = 0; j < 40; j++)
{
if (j%2 == 0){
pHB[i][j] = Newdata[i][j]; // sets the values in the new array
for(int i =0; i <20; i++){
for(int k = 0; k <20; k++){
pHB[i][k] = pHB[i][j];

}
}
}
cout << setw(10) << pHB[i][j%2==0]<<" "; // Test to see if the array was successfully uploaded
}
cout << endl; //necessary to set up the dimensions of the 2D array
}
cout << endl; //new line to reduce clutter in the command window][/code]
Looks like you have a set of nested for loops inside a set of nested for loops. You're doing too much work.

You should only need one pair of for loops, to iterate over each dimension, and within that, assign to the new array.

Think of it this way: What if both arrays were the same size, and you were simply copying each array element 1:1. How would you write this?
Now, write it the same way, but skipping every other column.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    int original_array[20][40];
    int new_array[20][20]; // Half the columns
    
    for (int i = 0; i < 20; i++)
    {
        for (int j = 0; j < 40; j += 2) // NOTICE: += 2
        {
            // ... assign from old array to new array
            // careful of the new_array's j index! (hint: divide by 2)
        }
    }
}
Last edited on
Got it! Thanks!
Topic archived. No new replies allowed.