Write a C++ program using the concept of OOP to find the occurrence of a digit in a number.
Algorithm:
- Create a class DigitFinder with private members number, digit, and count and public member functions getData(), findOccurrence(), display(), and a constructor.
- In the constructor initialize count = 0
- In the getData() function, take input from the user for the number and digit to search for.
- In the findOccurrence() function, use a loop to iterate through each digit of the number.
- a. In each iteration, check if the current digit is equal to the digit to search for.
- b. If the current digit is equal to the digit to search for, increment the count by 1.
- In the display() function, display the result as "The digit DIGIT occurs COUNT times in NUMBER".
- In the main function, create an object of the DigitFinder class, call the functions getData(), findOccurrence(), and display() in order to get user input, find the occurrence of the digit and display the result.
- Exit the program.
Coding:
#include <iostream>
using namespace std;
class DigitFinder {
private:
int number, digit, count;
public:
DigitFinder() {
count = 0;
}
void getData() {
cout << "Enter a number: ";
cin >> number;
cout << "Enter a digit to search for: ";
cin >> digit;
}
void findOccurrence() {
int temp = number;
while (temp != 0) {
if (temp % 10 == digit) {
count++;
}
temp /= 10;
}
}
void display() {
cout << "The digit " << digit << " occurs " << count << " times in " << number << endl;
}
};
int main() {
DigitFinder obj;
obj.getData();
obj.findOccurrence();
obj.display();
return 0;
}
/*
Enter a number: 12356789
Enter a digit to search for: 5
The digit 5 occurs 1 times in 12356789
*/
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment