Write a C++ program using the concept of OOP to print all unique elements in an array


 Write a C++ program using the concept of OOP to print all unique elements in an array


Algorithm:

  1. Create a class called "UniqueFinder"
  2. Define a private array called "unique_elements"
  3. Define a private variable called "unique_count" to keep track of the number of unique elements
  4. Define a public function called "find_unique()" that takes in an array of integers as an input
  5. Iterate through the input array and use an if statement to check if the current element is already in the unique_elements array
  6. If the element is not found in the unique_elements array, add it to the array and increment the unique_count
  7. Define a public function called "print_unique()" that prints out the unique elements in the array

C++ Program:


#include <iostream>
 
class UniqueFinder {
private:
    int unique_elements[100];
    int unique_count = 0;
 
public:
    void find_unique(int input_array[], int size) {
        for (int i = 0; i < size; i++) {
            bool found = false;
            for (int j = 0; j < unique_count; j++) {
                if (input_array[i] == unique_elements[j]) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                unique_elements[unique_count] = input_array[i];
                unique_count++;
            }
        }
    }
 
    void print_unique() {
        std::cout << "Unique elements: ";
        for (int i = 0; i < unique_count; i++) {
            std::cout << unique_elements[i] << " ";
        }
        std::cout << std::endl;
    }
};
 
int main() {
    int input_array[100];
    int size;
    std::cout << "Enter the number of elements in the array: ";
    std::cin >> size;
    std::cout << "Enter the elements of the array: ";
    for(int i = 0; i< size; i++){
        std::cin >> input_array[i];
    }
 
    UniqueFinder finder;
    finder.find_unique(input_array, size);
    finder.print_unique();
 
    return 0;
}
 
 
/*
======Input/Output=====
Enter the number of elements in the array: 5
Enter the elements of the array: 1 2 2 3 3
Unique elements: 1 2 3
 
*/

#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment