Silviu Stroe
Silviu Stroe

Reputation: 1

Display first even and then odd elements in a C++array

I'm a C++ newb. I need to insert numbers to an array and then display first the odd numbers and then the even numbers in a single array. I've managed to create two separate arrays with the odd and even numbers but now I don't know how to sort them and put them back in a single array. I need your help to understand how to do this with basic C++ knowledge, so no advanced functions. Here's my code:

#include <iostream>
using namespace std;

int main()
{

    int N{ 0 }, vector[100], even[100], odd[100], unify[100], i{ 0 }, j{ 0 }, k{ 0 };

    cout << "Add the dimension: " << endl;
    cin >> N;
    cout << "Add the elements: " << endl;

    for (int i = 0; i < N; i++) {

        cout << "v[" << i << "]=" << endl;
        cin >> vector[i];
    }

    for (i = 0; i < N; i++) {
        if (vector[i] % 2 == 0) {
            even[j] = vector[i];
            j++;
        }
        else if (vector[i] % 2 != 0) {
            odd[k] = vector[i];
            k++;
        }
    }

    cout << "even elements are :" << endl;

    for (i = 0; i < j; i++) {
        cout << " " << even[i] << " ";
        cout << endl;
    }

    cout << "Odd elements are :" << endl;

    for (i = 0; i < k; i++) {
        cout << " " << odd[i] << " ";
        cout << endl;
    }

    return 0;
}

Upvotes: 0

Views: 1222

Answers (7)

Toby Speight
Toby Speight

Reputation: 30762

You want to partition the array into even and odd elements. The function for that is (drumroll...) std::partition(). Or perhaps std::stable_partition() if we need to retain the original order of elements.

There's also a std::ranges version of each of these, which will be more suitable for this application.

#include <algorithm>
#include <concepts>
#include <iostream>
#include <iterator>
#include <ranges>
#include <vector>

int main()
{
    static constexpr auto is_even =
        [](std::integral auto i){ return i % 2 == 0; };

    // Create our vector
    auto v = std::views::iota(1, 20) | std::ranges::to<std::vector>();

    // Partition it
    std::ranges::stable_partition(v, is_even);

    // And print
    std::ranges::copy(v, std::ostream_iterator<int>{std::cout, "\n"});
}

Output:

2
4
6
8
10
12
14
16
18
1
3
5
7
9
11
13
15
17
19

Upvotes: 0

jjjj
jjjj

Reputation: 1

int main() {
  const int size = 10;
  int arr[10];

  for (int i = 0; i < size; i++) {
    scanf("%d", &arr[i]);
  }

  for (int i = 0; i < size; i++) {
    if (arr[i] % 2 == 0) {
      printf("%d", arr[i]);
    }
  }

  for (int i = 0; i < size; i++) {
    if (arr[i] % 2 == 1) {
      printf("%d", arr[i]);
    }
  }
}

Upvotes: 0

You can use Bubble Sort Algorithm to sort whole input. After sorting them using if and put odd or even numbers in start of result array and and others after them. like below:

//Bubble Sort

 void bubbleSort(int arr[], int n)
    {
        int i, j;
        for (i = 0; i < n - 1; i++)
            // Last i elements are already 
            // in place
            for (j = 0; j < n - i - 1; j++)
                if (arr[j] > arr[j + 1])
                    swap(arr[j], arr[j + 1]);
    }
  

// Insert In array

int result[100];
if(odd[0]<even[0])
{
for (int i = 0; i < k; i++)
{result[i] = odd[i];}
for (int i = 0; i < j; i++)
{result[i+k] = even[i];}
}else
{
for (int i = 0; i < j; i++)
{result[i] = even[i];}
for (int i = 0; i < k; i++)
{result[i+k] = odd[i];}
}

Upvotes: -2

Silviu Stroe
Silviu Stroe

Reputation: 1

I managed to find the following solution. Thanks you all for your help.

 #include <iostream>
using namespace std;

int main()
{

   int N{0}, vector[100], even[100], odd[100], merge[100], i{0}, j{0}, k{0}, l{0};

   cout << "Add the dimension: " << endl;
   cin >> N;
   cout << "Add the elements: " << endl;

   for (int i = 0; i < N; i++)
   {

      cout << "v[" << i << "]=" << endl;
      cin >> vector[i];
   }

   for (i = 0; i < N; i++)
   {
      if (vector[i] % 2 == 0)
      {
         even[j] = vector[i];
         j++;
      }
      else if (vector[i] % 2 != 0)
      {
         odd[k] = vector[i];
         k++;
      }
   }

   cout << "even elements are :" << endl;

   for (i = 0; i < j; i++)
   {
      cout << " " << even[i] << " ";
      cout << endl;
   }

   cout << "Odd elements are :" << endl;

   for (i = 0; i < k; i++)
   {
      cout << " " << odd[i] << " ";
      cout << endl;
   }

   for (i = 0; i < k; i++)
   {
      merge[i] = odd[i];
   }
   for (int; i < j + k; i++)
   {

      merge[i] = even[i - k];
   }

   for (int i = 0; i < N; i++)
   {
      cout << merge[i] << endl;
   }
   return 0;
}

Upvotes: 0

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12322

If you have to just output the numbers in any order, or the order given in the input then just loop over the array twice and output first the even and then the odd numbers.

If you have to output the numbers in order than there is no way around sorting them. And then you can include the even/odd test in the comparison:

std::ranges::sort(vector, [](const int &lhs, const int &rhs) {
            return ((lhs % 2) < (rhs % 2)) || (lhs < rhs); });

or using a projection:

std::ranges::sort(vector, {}, [](const int &x) {
 return std::pair<bool, int>{x % 2 == 0, x}; });

If you can't use std::ranges::sort then implementing your own sort is left to the reader.

Upvotes: 0

Broothy
Broothy

Reputation: 721

If you don't need to store the values then you can simply run through the elements and print the odd and the even values to different stringstreams, then print the streams at the end:

#include <sstream>
#include <stddef.h>
#include <iostream>

int main () {

  std::stringstream oddStr;
  std::stringstream evenStr;

  static constexpr size_t vecSize{100};

  int vec[vecSize] = {10, 5, 7, /*other elements...*/ };

  for(size_t vecIndex = 0; vecIndex < vecSize; ++vecIndex) {
    if(vec[vecIndex] % 2 == 0) {
      evenStr << vec[vecIndex] << " ";
    } else {
      oddStr << vec[vecIndex] << " ";
    }
  }

  std::cout << "Even elements are:" << evenStr.rdbuf() << std::endl;
  std::cout << "Odd elements are:" << oddStr.rdbuf() << std::endl;
}

Storing and sorting the elements are always expensive.

Upvotes: 2

S.A.Parkhid
S.A.Parkhid

Reputation: 2868

Basically, it would be better to sort them first.

#include <iostream>

using namespace std;

int main()
{
    int numbers[5];
    int mergedArrays[5];
    int evenNumbers[5];
    int oddNumbers[5];
    
    for(int i=0;i<5;i++){
        cin>>numbers[i];
    }
    
    int temp=numbers[0];
    //bubble sort
    for(int i = 0; i<5; i++) 
    {
       for(int j = i+1; j<5; j++)
       {
          if(numbers[j] < numbers[i]) 
          {
             temp = numbers[i];
             numbers[i] = numbers[j];
             numbers[j] = temp;
          }
       }
   
    }
    
    int nEvens=0;
    int nOdds=0;

    for(int i = 0; i<5; i++) 
    {
      
       if(numbers[i]%2==0)
       {
           
           evenNumbers[nEvens]=numbers[i];
           nEvens++;
          
       }
       else if(numbers[i]%2!=0)
       {
           oddNumbers[nOdds]=numbers[i];
           nOdds++;
        
       }
    }
    
    
 
    
    int lastIndex=0;
    //copy evens
    
    for(int i = 0; i<nEvens; i++) 
    {
      
       mergedArrays[i]=evenNumbers[i];
       lastIndex=i;
    }
    
 
    
    //copy odds
    for(int i =lastIndex; i<nOdds; i++) 
    {
      
         mergedArrays[i]=oddNumbers[i];
    }

    return 0;
}

Upvotes: 0

Related Questions