Write a C++ program using the concept of OOP to count frequency of each digits of a number


Write a C++ program using the concept of OOP to count the frequency of each digits of a number.


Algorithm:

  1. Create a class DigitCounter with private members number, and count an array of size 10 to store frequency of each digits and public member functions getData(), countDigits(), display(), and a constructor.
  2. In the constructor initialize all the elements of count array to zero.
  3. In the getData() function, take input from the user for the number
  4. In the countDigits() function, use a loop to iterate through each digit of the number.
    1. a. In each iteration, count[temp % 10]++; where temp is the number
    2. b. update the temp by dividing it by 10.
  5. In the display() function, use a loop to iterate through the count array and for each non zero element at index i, display i occurs count[i] times
  6. In the main function, create an object of the DigitCounter class, call the functions getData(), countDigits(), and display() in order to get user input, count the frequency of each digit and display the result.
  7. Exit the program.


Coding:

#include <iostream>
using namespace std;
 
class DigitCounter {
private:
    int number;
    int count[10];
 
public:
    DigitCounter() {
        for(int i=0; i<10; i++)
            count[i] = 0;
    }
 
    void getData() {
        cout << "Enter a number: ";
        cin >> number;
    }
 
    void countDigits() {
        int temp = number;
        while (temp != 0) {
            count[temp % 10]++;
            temp /= 10;
        }
    }
 
    void display() {
        for(int i=0; i<10; i++) {
            if(count[i] != 0) 
                cout << i << " occurs " << count[i] << " times" << endl;
        }
    }
};
 
int main() {
    DigitCounter obj;
    obj.getData();
    obj.countDigits();
    obj.display();
    return 0;
}
/*
Enter a number: 12356789
1 occurs 1 times
2 occurs 1 times
3 occurs 1 times
5 occurs 1 times
6 occurs 1 times
7 occurs 1 times
8 occurs 1 times
9 occurs 1 times
*/


#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment