C++ Program to Calculate Mode of Numbers

C++ Program to Calculate Mode of Numbers

In statistics, the mode of a dataset is the number that occurs most frequently. Unlike the mean or median, the mode can reveal patterns in data, such as the most common scores in an exam or popular product choices in a store. Learning how to calculate the mode in C++ helps beginners understand arrays, vectors, maps, and basic algorithms, making it a useful exercise for improving programming skills.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Program 1: Calculate the Mode Using Arrays

This program demonstrates how to find the mode of numbers stored in an array. It counts how many times each number appears and identifies the number(s) with the highest frequency.

#include <iostream>

using namespace std;

int main() {

    int n;

    cout << "Enter number of elements: " << endl;
    cin >> n;

    int arr[n];

    cout << "Enter " << n << " numbers: " << endl;

    for(int i = 0; i < n; i++)
        cin >> arr[i];

    int maxCount = 0;
    int mode = arr[0];

    for(int i = 0; i < n; i++) {

        int count = 0;

        for(int j = 0; j < n; j++) {

            if(arr[j] == arr[i])
                count++;

        }

        if(count > maxCount) {

            maxCount = count;
            mode = arr[i];
        }

    }

    cout << "Mode: " << mode << endl;

    return 0;

}

This program works by comparing each element with every other element to count its occurrences. The number with the highest count becomes the mode. Beginners can understand this as a simple approach to track frequency, though it can be optimized for larger datasets.

Program 2: Mode Using Predefined Array

This program calculates the mode of a predefined array, allowing beginners to focus on logic without entering data manually.

#include <iostream>

using namespace std;

int main() {

    int arr[] {4, 2, 4, 3, 2, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    int maxCount = 0;
    int mode = arr[0];

    for(int i = 0; i < n; i++) {

        int count = 0;

        for(int j = 0; j < n; j++) {

            if(arr[j] == arr[i])
                count++;
        }

        if(count > maxCount) {
            maxCount = count;
            mode = arr[i];
        }

    }

    cout << "Mode: " << mode << endl;

    return 0;

}

Using a predefined array helps beginners understand how the logic works on fixed datasets and how to analyze frequency without user input.

Program 3: Calculate Mode Using Vectors and Maps

Here, we use a vector to store numbers and a map to count frequencies. This method is more efficient for larger datasets and allows handling multiple modes.

#include <iostream>
#include <vector>
#include <map>

using namespace std;

int main() {

    int n;

    cout << "Enter number of elements: " << endl;
    cin >> n;

    vector<int> numbers(n);

    cout << "Enter " << n << " numbers: ";

    for(int i = 0; i < n; i++)
        cin >> numbers[i];

    map<int,int> frequency;

    for(int num : numbers)
        frequency[num]++;

    int maxCount = 0;

    for(auto pair : frequency)

        if(pair.second > maxCount)
            maxCount = pair.second;

    cout << "Mode(s): ";

    for(auto pair : frequency)

        if(pair.second == maxCount)
            cout << pair.first << " ";

    cout << endl;

    return 0;

}

This program uses a map to store each number’s frequency, making it faster and cleaner. It also handles cases where multiple numbers appear with the same highest frequency, making it suitable for multimodal datasets. Beginners can see how vectors and maps work together to solve common programming problems efficiently.

Program 4: Mode Using Predefined Vector

This program uses a predefined vector, making it easy to test and analyze frequency without manual input.

#include <iostream>
#include <vector>
#include <map>

using namespace std;

int main() {

    vector<int> numbers {5, 1, 5, 2, 3, 5, 2};

    map<int,int> frequency;

    for(int num : numbers)
        frequency[num]++;

    int maxCount = 0;

    for(auto pair : frequency)
        if(pair.second > maxCount)
            maxCount = pair.second;

    cout << "Mode(s): ";

    for(auto pair : frequency)

        if(pair.second == maxCount)
            cout << pair.first << " ";

    cout << endl;

    return 0;

}

Using a predefined vector demonstrates how dynamic containers like vectors work with maps for frequency counting, offering flexibility and readability.

Frequently Asked Questions (FAQ)

Q1: What happens if multiple numbers have the same highest frequency?
The second program correctly handles this by printing all numbers that share the maximum frequency.

Q2: Can I use arrays instead of vectors?
Yes, arrays work fine, but vectors are more flexible for datasets whose size is not known at compile time.

Q3: Why use a map instead of nested loops?
Using a map avoids repeated counting of elements, reducing time complexity from O(n²) to O(n).

Q4: Can the program find the mode of decimal numbers?
Yes, you can use float or double with a map, but rounding issues may require additional handling.

Conclusion

Calculating the mode in C++ is a great way for beginners to practice arrays, vectors, maps, and loops. Whether using simple arrays or more advanced structures like maps, understanding these methods improves coding skills and prepares learners for handling real-world datasets. By experimenting with different approaches, beginners can strengthen their grasp of both C++ syntax and basic algorithmic thinking.

Additional & References

To continue learning, beginners should practice using arrays, vectors, and maps for frequency analysis in different datasets. Experimenting with these approaches will improve problem-solving skills and efficiency in C++.

Scroll to Top