A C++ program that counts the occurrences of each digit in a given number:
cpp#include <iostream>
#include <map>
int main() {
long long number;
std::cout << "Enter a number: ";
std::cin >> number;
std::map<int, int> digitCount;
while (number > 0) {
int digit = number % 10;
digitCount[digit]++;
number /= 10;
}
std::cout << "Digit occurrences:" << std::endl;
for (const auto& entry : digitCount) {
std::cout << "Digit " << entry.first << ": " << entry.second << " times" << std::endl;
}
return 0;
}
Explanation:
- The program uses a
std::map
nameddigitCount
to store the counts of each digit in the input number. - The program takes an input number from the user.
- The program then enters a loop where it repeatedly extracts the last digit of the number using the modulo operator
%
and divides the number by 10 to remove the last digit. - The extracted digit is inserted into the
digitCount
map, and its count is incremented. - The loop continues until the number becomes zero.
- After processing all digits, the program prints out the occurrences of each digit.
- The
for
loop iterates through thedigitCount
map and prints the digit and its corresponding count.
For example, if the user inputs 12233442
, the output might be:
cppEnter a number: 12233442
Digit occurrences:
Digit 1: 2 times
Digit 2: 4 times
Digit 3: 2 times
Digit 4: 2 times
In this example, the program counts and displays the occurrences of each digit in the input number.
No comments:
Post a Comment