C
Swap Two Numbers
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
Reverse a String
void reverseString(char *str) {
int len = strlen(str);
for (int i = 0; i < len / 2; ++i) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
Find the Largest Element in an Array
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; ++i) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
Calculate the Sum of Elements in an Array
int sumArray(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; ++i) {
sum += arr[i];
}
return sum;
}
Sort an Array using Bubble Sort
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
JavaScript
Remove Duplicates from an Array
function removeDuplicates(arr) {
return [...new Set(arr)];
}
Check if a String is a Palindrome
function isPalindrome(str) {
const cleaned = str.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
return cleaned === cleaned.split("").reverse().join("");
}
Sort an Array of Numbers
function sortArray(arr) {
return arr.slice().sort((a, b) => a - b);
}
Remove item by value from Array
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
Replace all occurrences of substring
function replaceAllOccurences(string, search, replacement) {
return string.split(search).join(replacement);
}