From 4894f8cd6750febe47c1590e940b3f8db84804eb Mon Sep 17 00:00:00 2001 From: Shivani-Sharma-23 Date: Sat, 6 Jan 2024 18:42:50 +0530 Subject: [PATCH] Frequency of each element in an array --- .../CPlusPlus/Arrays/frequency-of-number.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 algorithms/CPlusPlus/Arrays/frequency-of-number.cpp diff --git a/algorithms/CPlusPlus/Arrays/frequency-of-number.cpp b/algorithms/CPlusPlus/Arrays/frequency-of-number.cpp new file mode 100644 index 000000000..17d7f9c6d --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/frequency-of-number.cpp @@ -0,0 +1,32 @@ +#include +#include +#include + +void countFrequency(const std::vector& array) { + std::unordered_map frequencyMap; + + for (int element : array) { + frequencyMap[element]++; + } + + for (const auto& pair : frequencyMap) { + std::cout << "Element " << pair.first << ": " << pair.second << " times\n"; + } +} + +int main() { + int size; + std::cout << "Enter the size of the array: "; + std::cin >> size; + + std::vector array(size); + std::cout << "Enter the elements of the array:\n"; + for (int i = 0; i < size; ++i) { + std::cout << "Element " << i + 1 << ": "; + std::cin >> array[i]; + } + + countFrequency(array); + + return 0; +} \ No newline at end of file