Defining Multidimensional Arrays in C programming
Defining Multidimensional Arrays in C
In C programming, a multidimensional array is an array of arrays. It allows you to store data in a table-like format. The most common type of multidimensional array is the two-dimensional array, but C supports arrays with more dimensions as well.
Syntax
The general syntax for defining a multidimensional array is:
data_type array_name[size1][size2]...[sizeN];
Here, size1
, size2
, ..., sizeN
specify the number of elements in each dimension.
Example
Here is an example of defining and initializing a two-dimensional array:
#include <stdio.h>
int main() {
// Defining a 2x3 multidimensional array
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Accessing and printing elements of the array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("arr[%d][%d] = %d\\n", i, j, arr[i][j]);
}
}
return 0;
}
Explanation
int arr[2][3];
- Declares a two-dimensional array with 2 rows and 3 columns.{ {1, 2, 3}, {4, 5, 6} }
- Initializes the array with values.- The nested
for
loops are used to access and print each element of the array.
Note: You can define arrays with more than two dimensions. For example, a three-dimensional array would be defined as
data_type array_name[size1][size2][size3];
.
Comments
Post a Comment