4-Dimensional Array in C/C++
An array is a data structure where we store the data or value in linear order and memory is assigned to the values in a contiguous manner. In arrays, the data type of the values stored should be similar.
arr = [1,2,3,4,6] is the integer array where the number of elements is five, and it is a single-dimension array.
We can create one-dimensional, two-dimensional or multidimensional arrays in C or C++ in both languages.
A two-dimensional array is nothing but just a series of 1-D arrays connected in another direction.
So 2-D arrays generally are in the form of a matrix or grid.
This is the example of a 4X4 two-dimensional integer array, where the number of elements is 16.
Three-dimensional arrays are the series or group of two-dimensional arrays in the 3rd direction. They are generally referred to as cubes or cuboids.
This is the example of a 2x2x3 three-dimensional integer array, where the number of elements is 12, which can be easily calculated by multiplying the dimensions.(2x2x3 = 12).
If we talk about four-dimensional arrays, then we can visualize them as 3-dimensional arrays connected in the fourth direction.
For the 4-dimensional array general syntax would be:
data_type array_name [element1][element2][element3][element4];
In the above example, the 4-dimensional array is initialized, and the total number of elements is 4x5x1x6, which is 120.
4-dimensional arrays are too complex and difficult to visualize.
Determining the Length of the Array
If we want to get the total number of elements present in the array, then we can use the 'sizeof' operator, which gives the total number of bytes used by the variable, and we can divide it by the number of bytes used by a single variable.
In the above example of a 4-d array, we have 16 elements in the array. As we know, one integer variable takes 4 bytes of the memory, so the whole array will definitely take 16x4, which is 64 bytes of memory.
Total elements = total array size (In bytes)/one element size(In bytes)
In general, an array can have many dimensions, and an array of n-dimension can be represented as follows:
Where d1,d2….dn-1 are the number of elements in the nth direction. To calculate the number of elements in the array of n dimensions, we can use the following formula:
Number of elements = d0xd1xd2…..dn-1
In the general scenario, we work on mostly 1dimension, 2-dimensional and 3-dimensional arrays, but in real life, if we plot any problem, it can have many dimensions.