C++ program to sort the array in even-odd form using class

Given an array of integers, we to sort its elements in even-odd form using the class and object approach.
Submitted by Shubh Pachori, on September 14, 2022

Example:

Input: 
[0]: 8
[1]: 4
[2]: 3
[3]: 5
[4]: 8
[5]: 0
[6]: 9
[7]: 6
[8]: 1
[9]: 7

Output: 
Sorted Array:
8 4 8 0 6 3 5 9 1 7

C++ code to sort the array in even-odd form using the class and object approach

#include <iostream>
using namespace std;

// create a class
class Array {
  // private data member
 private:
  int arr[10];

  // public member functions
 public:
  // getArray() function to insert 
  // array elements
  void getArray() {
    for (int index = 0; index < 10; index++) {
      cout << "[" << index << "]: ";
      cin >> arr[index];
    }
  }

  // sortEvenOdd() function to sort the
  // array in even-odd form
  void sortEvenOdd() {
    // initialising int type variable to
    // perform operations
    int temp[10], index_1, index_2 = 0;

    // for loop to traverse the whole array
    for (index_1 = 0; index_1 < 10; index_1++) {
      // if condition for even numbers
      // of the array
      if (arr[index_1] % 2 == 0) {
        // copying values at index of arr to temp
        temp[index_2] = arr[index_1];

        index_2++;
      }
    }

    // for loop to traverse the whole array
    for (index_1 = 0; index_1 < 10; index_1++) {
      // if condition for odd numbers
      // of the array
      if (arr[index_1] % 2 != 0) {
        // copying values at index of arr to temp
        temp[index_2] = arr[index_1];

        index_2++;
      }
    }

    cout << "\nSorted Array:" << endl;

    // printing the sorted array
    for (index_1 = 0; index_1 < 10; index_1++) {
      cout << temp[index_1] << " ";
    }
  }
};

int main() {
  // create an object
  Array A;

  // calling getArray() function to 
  // insert the array
  A.getArray();

  // calling sortEvenOdd() function to 
  // sort the array in even-odd form
  A.sortEvenOdd();

  return 0;
}

Output:

[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 9
[9]: 10
Sorted Array:
2 4 6 8 10 1 3 5 7 9

Explanation:

In the above code, we have created a class Array, one int type array data members arr[10] to store the elements of the array, and public member functions getArray() and sortEvenOdd() to store the array elements and to sort the array in even-odd form.

In the main() function, we are creating an object A of class Array, reading the inputted array by the user using getArray() function, and finally calling the sortEvenOdd() member function to sort the array in even-odd form. The sortEvenOdd() function contains the logic to sort the array in even-odd form and printing the result.

C++ Class and Object Programs (Set 2) »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.