×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to separate the even and odd numbers in the array using class

Submitted by Shubh Pachori, on September 14, 2022

Problem statement

Given an array of integers, we have to separate the even and odd numbers in the array using the class and object approach.

Example:

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

Even 	Odd
8
4
	3
	5
8
0
	9
6
	1
	7

C++ code to separate the even and odd numbers in the array 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];
    }
  }

  // evenOdd() function to separate even
  // and odd numbers in the array
  void evenOdd() {
    cout << "\nSeparated Numbers : " << endl;

    cout << "\nEven \tOdd" << endl;

    // for loop to traverse the whole array
    for (int index = 0; index < 10; index++) {
      // if condition to print even numbers of the array
      if (arr[index] % 2 == 0) {
        cout << arr[index] << endl;
      }

      // else condition to print odd numbers of the array
      else {
        cout << "\t" << arr[index] << endl;
      }
    }
  }
};

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

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

  // calling evenOdd() function to separate even
  // and odd numbers in the array
  A.evenOdd();

  return 0;
}

Output

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

Separated Numbers : 

Even 	Odd
	1
2
	3
4
	5
6
	7
8
	9
10

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 evenOdd() to store the array elements and to separate even and odd numbers in the array.

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 evenOdd() member function to separate even and odd numbers in the array. The evenOdd() function contains the logic to separate even and odd numbers in the array and printing the result.

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

Comments and Discussions!

Load comments ↻





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