Arrays
In computer programming, an array is a data structure that stores a fixed-size sequence of elements of the same type. It is used to organize and manipulate collections of data effectively.
Arrays can be one-dimensional, two-dimensional (matrices), or multidimensional. A one-dimensional array uses a single index. A two-dimensional array uses two indices—one for rows and one for columns.
Arrays are used for storing numbers, characters, or objects, iterating through data, searching, sorting, and modifying values. They provide fast and direct access using index numbers.
In short summary:
- Array is a collection of similar data types grouped under one name.
- It is also called a vector.
- All elements are accessed using index values.
- Supported by almost all programming languages.
Example:
| 0 | 1 | 2 | 3 | 4 |
|---|
| 15 |
Different ways of declaring and initializing arrays:
| 0 | 1 | 2 | 3 | 4 |
|---|
| ? | ? | ? | ? | ? |
Garbage values
| 0 | 1 | 2 | 3 | 4 |
|---|
| 2 | 4 | 6 | 8 | 10 |
| 0 | 1 | 2 | 3 | 4 |
|---|
| 2 | 4 | 0 | 0 | 0 |
| 0 | 1 | 2 | 3 | 4 |
|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 2 | 3 | 4 |
|---|
| 2 | 4 | 6 | 8 | 10 |
Traversing an array:
for (i = 0; i < 5; i++) {
printf("%d", A[i]);
}
• Array elements can also be accessed using pointer notation.
for (i = 0; i < 5; i++) {
printf("%d", A[i]);
printf("%d", A[2]);
printf("%d", 2[A]);
printf("%d", *(A + 2));
}