An array is a collection of variables of the same data type stored at contiguous memory locations. Arrays allow you to manage large amounts of data efficiently by using a single variable name with an index.
Why Use Arrays?
- Arrays simplify the management of related data.
- They allow accessing and manipulating data using indices.
- Useful for tasks involving large datasets, like sorting or searching.
Types of Arrays
- One-Dimensional Arrays
- A linear collection of elements.
- Two-Dimensional Arrays
- Used for tabular data (like a matrix).
- Multi-Dimensional Arrays
- Higher-dimensional arrays for complex data structures.
1. One-Dimensional Arrays
Declaration:
Initialization:
Accessing Elements:
- Use the index to access elements (indices start from
0
). - Example:
arr[0]
accesses the first element.
Example Program:
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf(“Element at index %d: %d\n”, i, arr[i]);
}
return 0;
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
2. Two-Dimensional Arrays
Declaration:
Initialization:
Accessing Elements:
- Use two indices:
matrix[row][column]
.
Example Program: