C++ program using the concept of OOP to count the frequency of each element of an array
Algorithm and C++ program that counts the frequency of each element in an array using the concept of object-oriented programming (OOP):
Algorithm:
- Create a class called "Counter"
- Define a private array called "frequency" with size equal to the maximum element in the array
- Define a public function called "count_frequency()" that takes in an array of integers as an input
- Iterate through the input array and use the current element as the index to increment the corresponding element in the frequency array
- Define a public function called "print_frequency()" that prints out the frequency of each element in the array
C++ Program:
#include <iostream>
class Counter {
private:
int frequency[100];
public:
void count_frequency(int input_array[], int size) {
for (int i = 0; i < size; i++) {
frequency[input_array[i]]++;
}
}
void print_frequency() {
for (int i = 0; i < 100; i++) {
if (frequency[i] != 0) {
std::cout << "Element " << i << " occurs " << frequency[i] << " times." << std::endl;
}
}
}
};
int main() {
int input_array[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
int size = sizeof(input_array) / sizeof(input_array[0]);
Counter counter;
counter.count_frequency(input_array, size);
counter.print_frequency();
return 0;
}
/*
======Input/Output=====
int input_array[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
Element 1 occurs 1 times.
Element 2 occurs 2 times.
Element 3 occurs 3 times.
Element 4 occurs 4 times.
*/
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment