Index
What is Array ?
An array is a collection of elements of the same type stored in contiguous memory locations. It allows easy access to elements using an index.
Here are some key points about arrays in DSA:
- Contiguous Memory Allocation: Arrays allocate memory in a contiguous block, meaning that elements are stored one after the other in memory. This allows for efficient access to elements using their indices.
- Fixed Size: Arrays have a fixed size, meaning that the number of elements they can hold is predetermined at the time of declaration. Once an array is created, its size typically cannot be changed dynamically.
- Zero-based Indexing: In most programming languages, arrays are zero-indexed, meaning that the index of the first element is 0, the index of the second element is 1, and so on.
- Random Access: Arrays support constant-time access to elements by index. Given an index, you can directly access the element stored at that index without traversing the entire array.
- Operations on Arrays:
- Accessing: You can access individual elements of an array using their indices.
- Insertion/Deletion: Inserting or deleting elements in an array can be inefficient if it requires shifting elements.
- Searching: Searching for an element in an array can be done using techniques like linear search or binary search (for sorted arrays).
- Sorting: Arrays can be sorted using various sorting algorithms such as bubble sort, insertion sort, merge sort, quicksort, etc.
- Manipulation: You can modify elements in an array based on your requirements.
- Multidimensional Arrays: Arrays can have more than one dimension, creating structures like matrices or tables. Multidimensional arrays can be implemented as arrays of arrays or using other data structures like dynamically allocated arrays of pointers.
- Memory Efficiency: Arrays are memory-efficient because they store elements in contiguous memory locations, allowing for efficient memory access and cache utilization.
Example of Array in Real Life
Imagine an egg tray with 6 slots. Each slot (index) can hold an egg (element)
+----+----+----+----+----+----+
| 10 | 20 | 30 | 40 | 50 | 60 |
+----+----+----+----+----+----+
0 1 2 3 4 5 <- Index
Here, arr[0] = 10
, arr[1] = 20
, and so on.
Key Features of Array
✔ Fixed Size – Cannot grow dynamically.
✔ Same Data Type – Stores elements of the same type.
✔ Indexing – Access elements using indices (starting from 0).
✔ Efficient Access – Accessing an element takes O(1) time.
Declaring an Array in C
int arr[5]; // Declares an array of size 5
Initializing an Array in C
int arr[5] = {10, 20, 30, 40, 50}; // Initializes with values
Example of Array in C
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50}; // Declare and initialize an array
// Access and print elements
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:
10 20 30 40 50