An Array is a collection of elements that are stored in contiguous memory locations. Arrays allow for the storage of multiple elements of the same type and are used widely in data structures and algorithms. Arrays provide fast access to elements through indices, making them an essential data structure in programming.
An Array is a data structure that can store multiple values of the same type under a single variable name. Each element in the array is identified by its index. Arrays are particularly useful when we need to store a collection of elements and need efficient access by index.
#include <stdio.h> #define MAX 5 void display(int arr[], int n) { for (int i = 0; i < n; i++) { printf("Element %d: %d\\n", i+1, arr[i]); } } int main() { int arr[MAX] = {10, 20, 30, 40, 50}; printf("Array Elements: \\n"); display(arr, MAX); printf("\\nAccessing Element at index 2: %d\\n", arr[2]); // Inserting new element (replacing index 3 value) arr[3] = 100; printf("Updated Array: \\n"); display(arr, MAX); return 0; }
Array Elements: Element 1: 10 Element 2: 20 Element 3: 30 Element 4: 40 Element 5: 50 Accessing Element at index 2: 30 Updated Array: Element 1: 10 Element 2: 20 Element 3: 30 Element 4: 100 Element 5: 50
Arrays can perform several common operations such as insertion, deletion, and searching. Here are some common operations:
void insert(int arr[], int n, int index, int value) { for (int i = n; i > index; i--) { arr[i] = arr[i - 1]; } arr[index] = value; } int main() { int arr[MAX] = {10, 20, 30, 40, 50}; int n = 5; printf("Before Insertion: \\n"); display(arr, n); // Inserting element at index 2 insert(arr, n, 2, 100); n++; printf("After Insertion: \\n"); display(arr, n); }
void delete(int arr[], int n, int index) { for (int i = index; i < n - 1; i++) { arr[i] = arr[i + 1]; } arr[n - 1] = 0; // Reset last element } int main() { int arr[MAX] = {10, 20, 30, 40, 50}; int n = 5; printf("Before Deletion: \\n"); display(arr, n); // Deleting element at index 3 delete(arr, n, 3); n--; printf("After Deletion: \\n"); display(arr, n); }
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!