In C programming, there aren't built-in functions specifically for arrays, but rather standard library functions that can be used with arrays.
Here are some commonly used functions for array manipulation along with examples:
Copying Array Elements.
Copies a specified number of bytes from the source array to the destination array.
#include <stdio.h> #include <string.h> int main() { int source[] = {1, 2, 3, 4, 5}; int destination[5]; // Copying elements from source array to destination array memcpy(destination, source, sizeof(source)); // Printing the destination array for (int i = 0; i < 5; i++) { printf("%d ", destination[i]); } printf("\n"); return 0; }
Filling Array Elements:
#include <stdio.h> #include <string.h> int main() { int arr[5]; // Filling the array with 0 memset(arr, 0, sizeof(arr)); // Printing the array for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
Sets the first n bytes of the memory area pointed to by the destination to the specified value.
#include <stdio.h> #include <string.h> int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {1, 2, 3, 4, 6}; // Comparing arrays int result = memcmp(arr1, arr2, sizeof(arr1)); if (result == 0) { printf("Arrays are equal.\n"); } else { printf("Arrays are not equal.\n"); } return 0; }
Comparing Array Contents.
Compares the first n bytes of two memory blocks.
#include <stdio.h> #include <stdlib.h> // Comparison function for qsort int compare(const void *a, const void *b) { return (*(int *)a - *(int *)b); } int main() { int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3}; // Sorting the array qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), compare); // Printing the sorted array for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
Sorting Array Elements.
#include <stdio.h> #include <stdlib.h> // Comparison function for bsearch int compare(const void *a, const void *b) { return (*(int *)a - *(int *)b); } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int key = 5; // Searching for key in the array int *result = (int *)bsearch(&key, arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), compare); if (result != NULL) { printf("Key found at index: %d\n", (int)(result - arr)); } else { printf("Key not found.\n"); } return 0; }
Sorts the elements of an array in ascending order using the quicksort algorithm.
Searching Array Elements:
Searches for a key in a sorted array using binary search.
These are some commonly used functions for array manipulation in C programming.
By using these functions effectively, we can perform various operations on arrays efficiently.