Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to separate even and odd numbers in an array in C++

Sarah Tanveer

In this shot, we will discuss how to separate odd and even numbers in a one-dimensional array.

Example of what the algorithm does

Code

#include <iostream>
using namespace std;

int main() {

  // declare the array
  const int size = 10;
  int values[size] = {2, 3, 4, 6, 8, 5, 1, 10, 7, 9};
  // temporary variable to aid in swapping
  int temp;

  // for loop to iterate through the array
  for(int i = 0; i < size; i++)
  {
    // if current element is even, do nothing
    if(values[i] % 2 == 0)
    {
      continue;
    }
    // else if current element is odd, 
    // run another for loop to check 
    // every subsequent element in the array
    for(int j = i + 1; j < size; j++)
    {
      // if the subsequent element is even
      if(values[j] % 2 == 0)
      {
        // swap the current element and this subsequent element
        temp = values[i];
        values[i] = values[j];
        values[j] = temp;
      }
    }
  }
  // for loop to print array
  for(int i = 0; i < size; i++)
  {
    cout << values[i] << " ";
  }
  return 0;
}

Explanation

  1. First, declare your int array.
  2. Run a for loop from i = 0 to i = size to iterate through the array.
  3. If the element is an even number, skip it.
  4. If the element is an odd number, run another 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.
  5. 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.
  6. The for loop will run to the end of the array and keep swapping until the even and odd numbers are separated.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring