In C programming, an array is a collection of elements of the same data type that are stored in contiguous memory locations.
Arrays provide a convenient way to store and manipulate multiple values of the same type under a single name.
Here's a brief overview of arrays in C:
To declare an array in C, we can specify the data type of the elements and the size of the array:
dataType arrayName[arraySize];
"dataType": Specifies the data type of the elements in the array.
"arrayName": Name of the array.
"arraySize": Number of elements in the array.
Arrays can be initialized at the time of declaration or later:
dataType arrayName[arraySize] = {value1, value2, ..., valueN};
Individual elements of an array are accessed using their index. The index of the first element is 0, and the index of the last element is arraySize - 1.
arrayName[index];
#include <stdio.h> int main() { int numbers[5] = {1, 2, 3, 4, 5}; // Accessing elements of the array printf("Element at index 0: %d\n", numbers[0]); // Output: 1 printf("Element at index 2: %d\n", numbers[2]); // Output: 3 return 0; }
In C99 and later, we can omit the size of the array if we provide an initializer list.
In this case, the size of the array is automatically determined based on the number of elements in the initializer list.
dataType arrayName[] = {value1, value2, ..., valueN};
C also supports multidimensional arrays, which are arrays of arrays.
For example, a two-dimensional array is declared as follows:
dataType arrayName[rowSize][colSize];
#include <stdio.h> int main() { int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; // Accessing elements of the two-dimensional array printf("Element at row 0, column 1: %d\n", matrix[0][1]); // Output: 2 printf("Element at row 1, column 2: %d\n", matrix[1][2]); // Output: 6 return 0; }
Arrays are fundamental data structures in C programming, extensively used for various purposes such as storing data, implementing algorithms, and passing data to functions.
Understanding arrays is crucial for writing efficient and effective C programs.