Unique Multi-dimentional Array Interaction
Make a program that declares the array:
int multi_array[4][4] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9,10,11,12 },
{13,14,15,16 }
};
Experiment with it, and notice how all array elements being placed next to eachother lets you access them using unique methods.
multi_array[2][1] and multi_array[1][5] both access the same element.
This can be done because of how all the elements are next to each other in memory.
Using this array, make 4 statements that print the element with value 7.
The first line should refer to the element normally (as the 3rd element of the 2nd array element). The following 3 should refer to the element by first accessing the first, third, and then fourth inner arrays.
Note that this task is for practice and illustration purposes. This functionality should not be used in your own programs.
Expected output
7777
Hint
You can use negative indecies with the access operator (multi_arrays[-x]).
Answer
#include <iostream>
int main()
{
int multi_array[4][4] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9,10,11,12 },
{13,14,15,16 }
};
std::cout << multi_array[1][2];
std::cout << multi_array[0][6];
std::cout << multi_array[2][-2];
std::cout << multi_array[3][-6];
}
Because all the values are placed next to each other, the data is essentially laid out as 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16.
[2][0] refers to 5, but we can change 0 to move up and down the list of numbers (1-16).
In pracsis, in the statement multi_array[x][y], increasing y by 1 moves the element we access up by 1.
Increasing x by 1 moves the element we access up by 4 (the size of the inner array).