Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

4 Dimensional Array in C/C++



4 Dimensional Array

The 4 dimensional array is an array of 3 dimensional arrays. Each 3 dimensional array is an array of 2 dimensional arrays and each 2 dimensional array is an array of 1 dimensional arrays. In this article, we will learn all about 4 dimensional arrays, how to create them and how to access their elements with examples in both C and C++.

Syntax to Create a 4D Array

Following is the syntax for declaring a 4 dimensional array in C/C++:

datatype array_name[dimension1][dimension2][dimension3][dimension4];

// Example
int arr[3][2][3][4];

Example of a 4 Dimensional Array

The section below shows implementation of a 4D array in C/C++.

C C++
#include <stdio.h>

int main() {
    int arr[2][2][2][3] = {
        {
            { {1, 2, 3}, {4, 5, 6} },
            { {1, 2, 3}, {4, 5, 6} }
        },
        {
            { {7, 8, 9}, {0, 2, 7} },
            { {7, 8, 9}, {0, 2, 7} }
        }
    };

    for (int i = 0; i < 2; i++) {
        printf("Block i = %d ", i);
        for (int j = 0; j < 2; j++) {
            printf("\n");
            for (int k = 0; k < 2; k++) {
                for (int l = 0; l < 3; l++) {
                    printf("%d ", arr[i][j][k][l]);
                }
                printf("\n");
            }
        }
        printf("\n");
    }

    return 0;
}

Output

The above program produces the following result:

Block i = 0 
1 2 3 
4 5 6 

1 2 3 
4 5 6 

Block i = 1 
7 8 9 
0 2 7 

7 8 9 
0 2 7 
#include <iostream>
using namespace std;

int main() {
    int arr[2][2][2][3] = {
        {
            { {1, 2, 3}, {4, 5, 6} },
            { {1, 2, 3}, {4, 5, 6} }
        },
        {
            { {7, 8, 9}, {0, 2, 7} },
            { {7, 8, 9}, {0, 2, 7} }
        }
    };

    for (int i = 0; i < 2; i++) {
        cout << "Block i = " << i;
        for (int j = 0; j < 2; j++) {
            cout  << endl;
            for (int k = 0; k < 2; k++) {
                for (int l = 0; l < 3; l++) {
                    cout << arr[i][j][k][l] << " ";
                }
                cout << endl;
            }
        }
    }

    return 0;
}

Output

The above program produces the following result:

Block i = 0 
1 2 3 
4 5 6 

1 2 3 
4 5 6 

Block i = 1 
7 8 9 
0 2 7 

7 8 9 
0 2 7 

Calculating Size of 4 Dimensional Array

The size of a 4D array in memory can be calculated by multiplying the number of elements in all dimensions with the size of the data type used. For example, if you have an array declared as int arr[3][2][3][4], and each integer takes 4 bytes of memory, then the total memory used will be:

3 * 2 * 3 * 4 * 4 = 288 bytes

You can also use sizeof in C/C++ to calculate the size in bytes:

int size = sizeof(arr);

// Output: 288
Updated on: 2025-05-29T19:12:08+05:30

914 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements