Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I started learning arrays in C++ and came over a little side note in the book ta

ID: 653044 • Letter: I

Question

I started learning arrays in C++ and came over a little side note in the book talking about 2D arrays in breif.

I tested it out and i was amazed that it could give the programmer the ability to store data or information and lay it out infront of him in a spread sheet format.

In a normal array to access elements i would simply do this:

int matrix[2] = { 1, 15};
But in 2D arrays :The only way it tells me to actually acces elements is by using a loop:

int fly[2][2];
int i = 0;
int n=0;
for(i=0; i<2; i++){
    for (n=0; n<2; n++){
        fly[i][n] =0;
    }
}
for(i=0; i<2; i++){
    for (n =0; n<2; n++){
        cout << fly[i][n]<< endl;
    }
}
I have tried accessing elements the old way:

int fly[2][2] = { 0};
but i noticed that this changes all the elements to 0

So..

Can anyone explain when i try accessing this 2D array like this all the elements change.

Is there another way to access 2D array elements without using a loop.

Thank you all.

Explanation / Answer

In a normal array to access elements i would simply do this:

int matrix[2] = { 1, 15};
You're declaring an array with that code. You're also assigning '1' to the int at index 0 and '15' to the int at index 1.

I have tried accessing elements the old way:

int fly[2][2] = { 0};
but i noticed that this changes all the elements to 0

That code doesn't assign '0' to the int at coordinates 2, 2... it creates a 2x2 array and tries to initialize it with the array that you've provided. Since the array is smaller than the size of the array that you're assigning to, the rest of the elements are simply initialized to 0. If you'd used '{15}' instead, you'd get a '15' in the first position, and '0' everywhere else. Try this instead:

int fly[2][2] = {{1, 2}, {3, 4}};
or even just:

int fly[2][2] = {1, 2, 3, 4};
In those cases, enough values are provided for every element of fly. If you this, though:

int fly[2][2] = {1, 2, 3};
you'll find that fly[1][1] is 0 because you didn't provide enough data.

Can anyone explain when i try accessing this 2D array like this all the elements change.

You can't really say that they "changed". You're only just creating the array, so other than the initialization you don't know what values are in the array. At any point after you create the array, you can access the array using the two subscripts:

int fly[2][2] = {{1, 2}, {3, 4}};
printf("%d %d %d %d ", fly[0][0], fly[0][1], fly[1][0], fly[1][1]); // prints '1 2 3 4'