Arrays
Arrays
An array is a collection of elements (values or variables), where all elements are of the same
type and stored in contiguous memory locations. Arrays are useful when you need to store
multiple elements of the same type and access them efficiently.
1.2 Why use Arrays?
Arrays allow you to store large amounts of data in a single variable.
Useful in data structures like matrices, graphs, heaps, and more.
1.3 Basic Syntax in C++
int arr[5]; // Declares an array of 5 integers
This creates an array called arr that can hold 5 integers. Array elements are indexed starting
from 0.
1.4 Array Declaration and Initialization
int arr[5] = {1, 2, 3, 4, 5}; // Array with 5 elements, initialized with values
Alternatively, you can declare an array without initializing:
int arr[5]; // Uninitialized array, default values depend on scope
2. Memory Layout and Accessing Elements (20 mins)
2.1 How Arrays are Stored in Memory
In C++, arrays are stored in contiguous memory locations. This means all elements
of the array are placed one after the other in memory.
For example, for an integer array int arr[5], assuming each integer takes 4 bytes, the
elements will be stored at addresses like &arr[0], &arr[1], &arr[2], etc.
2.2 Indexing in Arrays
Indexing starts at 0 in C++. So arr[0] refers to the first element, arr[1] refers to the
second, and so on.
The formula to access the memory address of an element at index i
Address = Base_Address + (i * size_of_element)
2.4 Array Traversal
Traversal means accessing each element of the array. Commonly, loops are used:
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
3. Array Operations (20 mins)
3.1 Insertion
Inserting an element into an array requires shifting other elements if you're inserting
at a position other than the end.
Example:
o To insert value = 10 at index 2:
arr[2] = 10;
3.2 Deletion
Deleting an element involves shifting elements to fill the gap left by the deleted
element.
for (int i = 2; i < n-1; i++) {
arr[i] = arr[i+1];
}
3.3 Updating Elements
Updating a value is straightforward:
arr[3] = 50; // Sets the 4th element to 50
3.4 Searching (Linear Search)
Linear search is a simple algorithm to search for an element in an array. It has O(n)
time complexity.
int search(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) return i;
}
return -1;
}