03 EKH Arrays
03 EKH Arrays
1. Introduction
A linear array is a data structure used to store a fixed-size sequential collection of elements of
the same type. It is also called a one-dimensional array.
An array is a collection of items of same data type stored at contiguous memory locations.
One-Dimensional Array
• Two-Dimensional Array: A two-dimensional array, often referred to as a matrix or 2D
array, is an array of arrays. It consists of rows and columns, forming a grid-like structure.
Elements in a 2D array are accessed using two indices, one for the row and one for the
column.
• Multi-Dimensional Array: Arrays can have more than two dimensions, leading to multi-
dimensional arrays. These are used when data needs to be organized in a multi-
dimensional grid.
Access O(1)
Search O(n)
Insertion O(n)
Deletion O(n)
Traversal in Array
Traversal in an array refers to the process of accessing each element in the array sequentially,
typically to perform a specific operation, such as searching, sorting, or modifying the elements.
Traversing an array is essential for a wide range of tasks in programming, and the most common
methods of traversal include iterating through the array using loops like for, while, or foreach.
Efficient traversal plays a critical role in algorithms that require scanning or manipulating data.
Examples:
Input: arr[] = [10, 20, 30, 40, 50]
Output: "10 20 30 40 50 "
Explanation: Just traverse and print the numbers.
Input: arr[] = [7, 8, 9, 1, 2]
Output: "7 8 9 1 2 "
Explanation: Just traverse and print the numbers.
Input: arr[] = [100, 200, 300, 400, 500]
Output: "100 200 300 400 500 "
Explanation: Just traverse and print the numbers.
Types of Array Traversal
There are mainly two types of array traversal:
1. Linear Traversal
Linear traversal is the process of visiting each element of an array sequentially, starting from the
first element and moving to the last element. During this traversal, each element is processed
(printed, modified, or checked) one after the other, in the order they are stored in the array. This
is the most common and straightforward way of accessing the elements of an array.
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Linear Traversal: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output
Linear Traversal: 1 2 3 4 5
Time Complexity: O(n)
Auxiliary Space: O(1)
2. Reverse Traversal
Reverse traversal is the process of visiting each element of an array starting from the last
element and moving towards the first element. This method is useful when you need to process
the elements of an array in reverse order. In this type of traversal, you begin from the last index
(the rightmost element) and work your way to the first index (the leftmost element).
// C Code
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Reverse Traversal: ");
for(int i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output
Reverse Traversal: 5 4 3 2 1
Time Complexity: O(n)
Auxiliary Space: O(1)
Insertion:
It means insert one or more elements into the array. We can insert an element at any position in
the array like beginning, end or at any given indexed position.
2. Linear Search
Definition:
Linear Search is a simple search algorithm that checks every element of the array sequentially
until the desired element is found or the array ends.
Algorithm:
1. Start from index 0.
2. Compare each element with the key.
3. If a match is found, return the index.
4. If not found after the last element, return -1.
Time Complexity:
3. Binary Search
Definition:
Binary Search is an efficient algorithm used to find an element in a sorted array by repeatedly
dividing the search interval in half.
• The algorithm requires two conditions –
1. The list must be sorted
2. One must have access to the middle element in any sublist.
• This means that one must essentially use a sorted array to hold the data
• But keeping data in a sorted array is very expensive when there are many insertions and
deletions (array limitation).
• In such situation, one may use a different data structure such as a linked list or a binary
search tree, to store the data.
Time Complexity:
5. Applications
• Linear Search: Useful when data is unsorted or very small.
• Binary Search: Ideal for large, sorted data like dictionaries, databases, or index tables.
Input:
• Array A of size m (sorted)
• Array B of size n (sorted)
Output:
• Array C of size m + n containing all elements from A and B, sorted
Idea:
• Use two pointers (or indices) to traverse both arrays.
• Compare the elements and insert the smaller one into the result array.
• If one array is exhausted, copy the remaining elements of the other.
Step-by-Step Algorithm:
1. Initialize pointers:
i = 0 // Pointer for array A
j = 0 // Pointer for array B
k = 0 // Pointer for result array C
Time Complexity:
• O(m + n): Each element from both arrays is processed once.
Example:
Input:
A = [1, 3, 5]
B = [2, 4, 6]
Output:
C = [1, 2, 3, 4, 5, 6]
1. Matrix Representation in C
• A matrix is stored as a 2D array.
• Syntax: dataType matrix[row][column];
• For example, a 3x3 matrix is represented as int matrix[3][3];
• Each element is accessed using two indices: matrix[i][j] (i = row, j = column)
2. Matrix Addition
Conditions:
• Both matrices must have the same dimensions (i.e., same number of rows and columns).
Operation:
• Add corresponding elements from both matrices:
o result[i][j] = A[i][j] + B[i][j]
3. Matrix Subtraction
Conditions:
• Like addition, both matrices must have identical dimensions.
Operation:
• Subtract elements of matrix B from A:
o result[i][j] = A[i][j] - B[i][j]
4. Matrix Multiplication
Conditions:
• If matrix A is of size m × n and matrix B is of size n × p, then:
o The result matrix will be of size m × p.
Operation:
• Multiply each row of A with each column of B:
o result[i][j] = A[i][0] × B[0][j] + A[i][1] × B[1][j] + ... + A[i][n-1] × B[n-1][j]
• It involves dot product of row and column vectors.
5. Transpose of a Matrix
Objective:
• To flip a matrix over its diagonal.
• Rows become columns, and columns become rows.
Operation:
• transpose[j][i] = matrix[i][j]
• Useful in mathematical applications and optimization.
3. Array of Pointers
Definition:
• An array of pointers is an array where each element is a pointer.
• Used to point to individual elements (or arrays) in memory.
Syntax:
int *arr[3]; // array of 3 integer pointers
Example Use Case:
int a = 10, b = 20, c = 30;
int *arr[3] = { &a, &b, &c };
• arr[0] points to a, arr[1] to b, etc.
Accessing Values:
printf("%d", *arr[1]); // prints 20
4. Pointer to an Array
Definition:
• A pointer that points to an entire array, not just an element.
Syntax:
int (*ptr)[5]; // pointer to array of 5 integers
Use:
int arr[5] = {1, 2, 3, 4, 5};
ptr = &arr;
printf("%d", (*ptr)[2]); // prints 3
8. Caution
• Improper use can lead to:
o Memory leaks
o Dangling pointers
o Segmentation faults
Summary Table
Function Purpose
malloc() Allocates uninitialized memory
calloc() Allocates zero-initialized memory
realloc() Changes size of allocated memory
free() Releases previously allocated memory
7. Common Mistakes
• Not checking NULL after malloc() or calloc()
• Accessing memory after free()
• Memory leaks: Not calling free() leads to wasted memory
• Double free: Freeing the same memory twice
Summary Table
calloc() (zeros)
Function Initializes? Can Resize? Needs Free?
realloc() -
free() - - -