split an array into smaller arrays in C
Code snippet on how to split an array into smaller arrays in C
// Split an array of 10 elements into two arrays, arr1 and arr2
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int arr1[5] = {}; // empty
int arr2[5] = {}; // empty
int j = 0;
for (int i = 0; i < 10; i++) {
if (i < 5) {
arr1[i] = arr[i];
}
else {
arr2[j] = arr[i];
j++;
}
}
This code splits an array of 10 elements into two smaller arrays, arr1 and arr2. It first declares an integer array of 10 elements and two empty integer arrays of 5 elements. A loop is then used to iterate through the original array, i.e. arr. The loop is initiated with a variable i initialized to 0 and is incremented for every iteration until i is greater than or equal to 10. If i is less than 5, the elements at index i of arr are assigned to arr1. Otherwise, elements from arr are assigned to arr2 in order. Then j is incremented, which ensures that elements of arr2 are assigned in the correct order. The result is two smaller arrays, arr1 and arr2, that each contain 5 elements.