Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Separate even and odd numbers of an array of integers. Put all even numbers first, and then odd numbers

C++ Array: Exercise-13 with Solution

Write a C++ program to separate even and odd numbers of an array of integers. Put all even numbers first, and then odd numbers.

Pictorial Presentation:

C++ Exercises: Separate even and odd numbers of an array of integers. Put all even numbers first, and then odd numbers

Sample Solution:

C++ Code :

#include<iostream>
using namespace std;
 
void swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
 
void segregateEvenOdd(int nums[], int size)
{
    int left_num = 0, right_num = size-1;
    while (left_num < right_num)
    {
         while (nums[left_num]%2 == 0 && left_num < right_num)
            left_num++;
 
        while (nums[right_num]%2 == 1 && left_num < right_num)
            right_num--;
 
        if (left_num < right_num)
        {
            swap(&nums[left_num], &nums[right_num]);
            left_num++;
            right_num--;
        }
    }
}
 
int main()
{
    int nums[] = {0, 1, 3, 4, 5, 6, 7, 8, 10};
    int n = sizeof(nums)/sizeof(nums[0]);
   	cout << "Original array: ";
    for (int i=0; i < n; i++) 
    cout << nums[i] <<" ";
    segregateEvenOdd(nums, n);
 
    printf("\nArray after divided: ");
      for (int i=0; i < n; i++) 
      cout << nums[i] <<" ";
        return 0;
     }

Sample Output:

Original array: 0 1 3 4 5 6 7 8 10 
Array after divided: 0 10 8 4 6 5 7 3 1  

Flowchart:

Flowchart: Separate even and odd numbers of an array of integers. Put all even numbers first, and then odd numbers

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to rearrange the elements of a given array of integers in zig-zag fashion way.
Next: Write a C++ program to separate 0s and 1s from a given array of values 0 and 1.

What is the difficulty level of this exercise?