C++ program using the concept of OOP to count the frequency of each element of an array


 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:

  1. Create a class called "Counter"
  2. Define a private array called "frequency" with size equal to the maximum element in the array
  3. Define a public function called "count_frequency()" that takes in an array of integers as an input
  4. Iterate through the input array and use the current element as the index to increment the corresponding element in the frequency array
  5. 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