Followers

Wednesday, August 16, 2023

C++ program that counts the occurrences of each digit in a given number

 


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:

  1. The program uses a std::map named digitCount to store the counts of each digit in the input number.
  2. The program takes an input number from the user.
  3. 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.
  4. The extracted digit is inserted into the digitCount map, and its count is incremented.
  5. The loop continues until the number becomes zero.
  6. After processing all digits, the program prints out the occurrences of each digit.
  7. The for loop iterates through the digitCount map and prints the digit and its corresponding count.

For example, if the user inputs 12233442, the output might be:

cpp
Enter 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