How to separate even and odd numbers in an array in C++
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.
Code
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;}
Explanation
- First, declare your
intarray. - Run a
forloop fromi = 0toi = sizeto iterate through the array. - If the element is an even number, skip it.
- If the element is an odd number, run another
forloop inside the first loop. This nestedforloop must run from the subsequent element to the end of the array (fromj = i + 1toj = size). Thisforloop will check every subsequent element in the array to determine where the current element needs to be moved. - If the subsequent element is an even number, swap it with the current element. If the subsequent element is an odd number, nothing is required.
- The
forloop will run to the end of the array and keep swapping until the even and odd numbers are separated.
Test yourself
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: