Separating even and odd numbers in an array is a common task in programming. In this Answer, we will discuss how to separate odd and even numbers in a one-dimensional array.
Let's implement the logic for separating the odd and even numbers in a one-dimensional array.
#include <iostream>using namespace std;int main() {// declare the arrayconst int size = 10;int values[size] = {2, 3, 4, 6, 8, 5, 1, 10, 7, 9};// temporary variable to aid in swappingint temp;// for loop to iterate through the arrayfor(int i = 0; i < size; i++){// if current element is even, do nothingif(values[i] % 2 == 0){continue;}// else if current element is odd,// run another for loop to check// every subsequent element in the arrayfor(int j = i + 1; j < size; j++){// if the subsequent element is evenif(values[j] % 2 == 0){// swap the current element and this subsequent elementtemp = values[i];values[i] = values[j];values[j] = temp;}}}// for loop to print arrayfor(int i = 0; i < size; i++){cout << values[i] << " ";}return 0;}
int
array.for
loop from i = 0
to i = size
to iterate through the array.for
loop inside the first loop. This nested for
loop must run from the subsequent element to the end of the array (from j = i + 1
to j = size
). This for
loop will check every subsequent element in the array to determine where the current element needs to be moved.for
loop will run to the end of the array and keep swapping until the even and odd numbers are separated.Challenge yourself by updating a given code snippet to rearrange an array in such a way that odd numbers are displayed first, followed by even numbers:
#include <iostream>void segregate(int values[], int size) {int temp;// for loop to iterate through the arrayfor (int i = 0; i < size; i++) {if (values[i] % 2 == 0) {continue;}for (int j = i + 1; j < size; j++) {if (values[j] % 2 == 0) {temp = values[i];values[i] = values[j];values[j] = temp;}}}}