“Partition an Array into Even and Odd Numbers Using Two-Array Logic in C”
C
Medium
4 views
Problem Description
I want to divide the array into two parts - the first half containing even numbers and the second half containing odd numbers - how do I approach the partitioning logic?
Official Solution
#include <stdio.h>
int main() {
int arr[] = {5, 2, 8, 7, 1, 4, 6, 9};
int size = sizeof(arr) / sizeof(arr[0]);
int result[size]; // new array for partitioned result
int evenIndex = 0;
int oddIndex = size - 1;
// Traverse original array
for (int i = 0; i < size; i++) {
if (arr[i] % 2 == 0) {
result[evenIndex] = arr[i];
evenIndex++;
} else {
result[oddIndex] = arr[i];
oddIndex--;
}
}
printf("Partitioned Array (Even first, Odd later):n");
for (int i = 0; i < size; i++) {
printf("%d ", result[i]);
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!