M4 What Are Arrays
M4 What Are Arrays
● Definition: Arrays are a collection of elements of the same data type stored in contiguous memory
locations.
● Why Use Arrays?
○ Store and manage large amounts of data.
○ Access elements using an index.
Syntax:
Copy code
data_type array_name[size];
Example:
Copy code
int numbers[5]; // Declares an integer array of size 5
One-Dimensional Arrays
Array Manipulation
Accessing Elements:
Copy code
int numbers[5] = {1, 2, 3, 4, 5};
printf("%d", numbers[0]); // Outputs: 1
Updating Elements:
Copy code
numbers[1] = 10; // Updates the second element to 10
Searching in an Array
● Linear Search:
○ Traverse the array to find the desired element.
Example:
Copy code
int search(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Element found at index i
}
}
return -1; // Element not found
}
○
● Binary Search:
○ Works on sorted arrays.
Example:
Copy code
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
Insertion
Example:
Copy code
void insert(int arr[], int *n, int pos, int value) {
for (int i = *n; i > pos; i--) {
arr[i] = arr[i - 1];
}
arr[pos] = value;
(*n)++;
}
Deletion
Example:
Copy code
void delete(int arr[], int *n, int pos) {
for (int i = pos; i < *n - 1; i++) {
arr[i] = arr[i + 1];
}
(*n)--;
}
Two-Dimensional Arrays
Syntax:
Copy code
data_type array_name[rows][columns];
Example:
Copy code
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
● Definition: Strings in C are arrays of characters ending with a null character (\0).
Example:
Copy code
char str[] = "Hello";
printf("%s", str);