Separate Even and Odd Numbers
C++
Medium
7 views
Problem Description
Rearrange array so all even numbers come before odd numbers. This teaches array partitioning logic.
Logic: Create two arrays for even/odd, then merge back
Official Solution
void question9_separate_even_odd() {
int arr[] = {12, 7, 18, 5, 20, 9};
int size = 6;
int result[6];
int index = 0;
// First add all even numbers
for(int i = 0; i < size; i++) {
if(arr[i] % 2 == 0) {
result[index++] = arr[i];
}
}
// Then add all odd numbers
for(int i = 0; i < size; i++) {
if(arr[i] % 2 != 0) {
result[index++] = arr[i];
}
}
cout << "Separated array: ";
for(int i = 0; i < size; i++) {
cout << result[i] << " ";
}
cout << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!