C++ program using the concept of OOP to count the total number of duplicate elements in an array
Algorithm:
- Create a class called "DuplicateCounter"
- Define a private variable called "duplicate_count" to keep track of the number of duplicate elements
- Define a public function called "count_duplicates()" that takes in an array of integers as an input
- Iterate through the input array and use nested loops to check if the current element is already in the remaining part of the array
- If the element is found again, increment the duplicate_count
- Define a public function called "print_duplicates()" that prints out the total number of duplicate elements in the array
C++ Program:
#include <iostream>
class DuplicateCounter {
private:
int duplicate_count = 0;
public:
void count_duplicates(int input_array[], int size) {
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (input_array[i] == input_array[j]) {
duplicate_count++;
break;
}
}
}
}
void print_duplicates() {
std::cout << "Total number of duplicate elements: " << duplicate_count << 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];
}
DuplicateCounter counter;
counter.count_duplicates(input_array, size);
counter.print_duplicates();
return 0;
}
/*
======Input/Output=====
Enter the number of elements in the array: 5
Enter the elements of the array: 1 2 2 3 3
Total number of duplicate elements: 4
*/
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment