A Guide to Different Types of Arrays in C - Episode 4
Understanding Array Varieties in C Programming
Arrays are fundamental constructs in C programming, enabling the storage of multiple data items under a single variable. In this episode, we explore the nuances of three array types: one-dimensional, two-dimensional, and multi-dimensional arrays.
Exploring One-Dimensional Arrays
A one-dimensional array is a sequential collection of elements of the same data type. Its declaration and access follow this syntax:
int numbers[5]; // Declare an array of 5 integers
numbers[0] = 10;
numbers[1] = 20;
// ...
For example, consider this illustration:
#include <stdio.h>
int main() {
int scores[3] = {85, 90, 78};
printf("First Score: %d\\n", scores[0]);
return 0;
}
Exploring Two-Dimensional Arrays
A two-dimensional array is like a grid with rows and columns. It's declared and accessed using this syntax:
int matrix[3][4]; // Declare a 3x4 matrix
matrix[0][0] = 10;
matrix[1][2] = 25;
// ...
For instance, consider this example:
#include <stdio.h>
int main() {
int table[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("Element at (1, 2): %d\\n", table[1][2]);
return 0;
}
Understanding Multi-Dimensional Arrays
A multi-dimensional array extends the concept to more dimensions. It's declared and accessed similarly:
int cube[2][3][4]; // Declare a 2x3x4 3D array
cube[0][1][2] = 42;
// ...
Here's a brief example:
#include <stdio.h>
int main() {
int space[2][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
printf("Element at (1, 0, 1): %d\\n", space[1][0][1]);
return 0;
}
0 Comments