In C programming, an array is a collection of elements of the same data type, stored in contiguous memory locations under a common name. It allows you to efficiently manage and access multiple values using a single variable.
Key Concepts:
- Declaration:
- Syntax:
data_type array_name[size];
- Example:
int numbers[5];
declares an array namednumbers
capable of storing 5 integers.
- Syntax:
- Accessing Elements:
- Use the array name followed by the index of the element within square brackets:
array_name[index]
. - Indices start from 0, so the first element is at index 0, the second at index 1, and so on.
- Use the array name followed by the index of the element within square brackets:
- Initialization:
- During declaration:
int scores[3] = {85, 92, 78};
- After declaration:
numbers[2] = 10;
- During declaration:
- Iteration:
- Use loops to access elements sequentially:
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
Important Points:
- Arrays are fixed in size: Once declared, their size cannot be changed.
- Out-of-bounds access: Attempting to access elements beyond the array’s bounds can lead to undefined behavior or program crashes.
- Arrays are passed by reference: When passed to functions, changes made within the function affect the original array.
- Arrays can be multidimensional: Arrays can have multiple dimensions to represent matrices, tables, etc.
Common Uses:
- Storing lists of values (e.g., student scores, product prices)
- Representing matrices for mathematical operations
- Implementing data structures like stacks and queues
- Handling strings (character arrays)
Arrays are fundamental data structures in C, providing a structured way to organize and manipulate collections of data.