C Multidimensional Arrays

In C programming language, a multidimensional array is an array of arrays, where each element of the array is itself an array. Multidimensional arrays are used to represent and manipulate data that has more than one dimension, such as a matrix or a table.

To declare a multidimensional array in C, you need to specify the data type of the elements and the dimensions of the array. The basic syntax for declaring a two-dimensional array is as follows:

Syntax :

data_type array_name[row_size][column_size];
 

Here, data_type is the data type of the elements in the array, array_name is the name of the array, row_size is the number of rows in the array, and column_size is the number of columns in the array. For example, to declare a 2-dimensional array of 3 rows and 4 columns that holds integers, you would use the following code:

int matrix[3][4];

This declares a 2-dimensional array named matrix with 3 rows and 4 columns, which can hold integers. The elements of the array are numbered from 0 to row_size - 1 for the row index and 0 to column_size - 1 for the column index.

You can initialize a multidimensional array with a nested set of curly braces, where each inner set of curly braces represents a row. For example, to initialize the matrix array with the following values:

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

 

you would use the following code:

int matrix[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };

You can access and modify individual elements of a multidimensional array using their row and column indices. For example, to print the element in the second row and third column of the matrix array, you would use the following code:

  
printf("%d\n", matrix[1][2]);

This prints the value of the element in the second row and third column of the matrix array, which is 7.

You can also use nested loops to iterate over the elements of a multidimensional array. For example, to print the elements of the matrix array, you would use the following code:

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        printf("%d ", matrix[i][j]);
    }
    printf("\n");
}

This uses a nested set of for loops to iterate over the rows and columns of the matrix array, and print the value of each element. The output of this program would be:

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

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

39285