Multidimensional Arrays

Hey all!

Ok, I am a c++ noob for sure. So thanx in advance to anyone who helps me!!!

What I am trying to do is write a for loop that puts the values it generates into a multidimensional array.

I am just looking for a basic example. I can usually figure things out if I have something to look off.

Thanks!
For each dimension of your array, you will need another for loop. For instance, if I have a 2-D array:

int myMatrix[ROWS][COLS];

Then I would fill it by saying something like:

1
2
3
4
5
for (int i = 0; i < ROWS; i++) {
   for (int j = 0; i < COLS; j++) {
      myMatrix[i][j] = i + j; // or whatever.
   }
}
BTW can anyone explain the use of multidimensional array, other than 2D, cuz it will get more complex the more u increase the dimensions of the array and how u r going to display it???
Well I guess the next dimension would be a 3d array. So:
int 3darray[5][5][5];
This would give you an array that is 5 ints tall, 5ints wide, 5 ints thick.
To add a values to all the parts you would need:
1
2
3
4
5
6
7
8
9
10
for(int i = 0;i < 5; i++)
{
       for(int u = 0; u < 5; u++)
       {
                for (int p = 0;p < 5; p++
                {
                           3darray[i][u][p] = (i + u + p);
                }
       } 
}


Displaying would be more complicated - depending on the way you want to display, I could think of a way but it wouldn't be very good.

I don't know about more then 3d arrays though.
Last edited on
And here's four-d arrays, for good measure.

1
2
3
4
5
6
7
8
9
10
11
12
13

void main(){
   int four_d_array[4][15][23][8];
   for(int i = 0; i < 4; i++){
      for(int j = 0; j < 15; j++){
         for(int k = 0; k < 23; k++){
            for(int l = 0; l < 8; l++){
               four_d_array[i][j][k][l] = whateverValue();
            }
         }
      }
   }
}


for five-d and beyond, You should be able to look at what we've given you and see the pattern emerging. Just add some more square brackets and for loops.
Ah, but is there any way to visualize a 4d array? Like see it in your mind as a block of cubes.
Topic archived. No new replies allowed.