Class Notes: Array
Definition:
An array is a data structure that stores a fixed-size sequential collection of elements of the same
data type.
Features:
Homogeneous elements: All elements are of the same type.
Fixed size: Size is defined at the time of declaration and cannot be changed.
Indexed: Elements can be accessed using indices (starting from 0).
Contiguous memory allocation.
Types of Arrays:
1.
One-Dimensional Array (1D):
Linear list of elements.
Example: int arr[5] = {1, 2, 3, 4, 5};
2.
Two-Dimensional Array (2D):
Table or matrix-like structure.
Example: int matrix[2][3] = {{1,2,3}, {4,5,6}};
3.
Multidimensional Array:
Arrays with more than two dimensions.
Rare in practice, mainly used in scientific computing.
Array Declaration & Initialization:
Syntax:
cpp
CopyEdit
datatype arrayName[size];
Example:
cpp
CopyEdit
int numbers[5]; // Declaration int numbers[5] = {10, 20, 30, 40, 50}; // Initialization
Common Operations:
Operation Description
Traversal Accessing each element of the array
Insertion Adding an element at a specific position
Deletion Removing an element from a specific position
Searching Finding the index of a given element
Updating Modifying an element at a given index
Advantages:
Fast access using index (O(1) time).
Simple and easy to implement.
Disadvantages:
Fixed size.
Insertion and deletion are expensive (O(n) time).
Use Cases:
Storing data collections (e.g., scores, IDs).
Lookup tables.
Temporary storage for algorithms like sorting and searching.