Numbers Histogram in c++

Sure! Here's an example of how you can create a numbers histogram in C++:

#include <iostream>
#include <vector>

void drawHistogram(const std::vector<int>& numbers) {
    // Find the maximum number in the input
    int maxNumber = 0;
    for (int num : numbers) {
        if (num > maxNumber) {
            maxNumber = num;
        }
    }

    // Create a frequency array to count the occurrences of each number
    std::vector<int> frequency(maxNumber + 1, 0);
    for (int num : numbers) {
        frequency[num]++;
    }

    // Draw the histogram
    for (int i = 0; i <= maxNumber; i++) {
        std::cout << i << ":\t";
        for (int j = 0; j < frequency[i]; j++) {
            std::cout << "*";
        }
        std::cout << std::endl;
    }
}

int main() {
    // Example usage
    std::vector<int> numbers = {2, 3, 5, 2, 4, 1, 3, 2, 4, 5};
    drawHistogram(numbers);

    return 0;
}

This code snippet demonstrates how to create a numbers histogram in C++. Here's a step-by-step explanation of the code:

  1. Include the necessary libraries: The code starts by including the <iostream> and <vector> libraries, which are necessary for input/output and using vectors respectively.

  2. Define the drawHistogram function: The drawHistogram function takes a vector of integers as input and does the following steps:

  3. Find the maximum number: It initializes a variable maxNumber to 0 and iterates over the input numbers to find the maximum number.
  4. Create a frequency array: It creates a vector frequency of size maxNumber + 1 and initializes all elements to 0. It then iterates over the input numbers again and increments the frequency count for each number.
  5. Draw the histogram: It iterates from 0 to maxNumber and for each number i, it prints the number followed by a colon and a tab character. It then prints a number of asterisks (*) based on the frequency count for that number.

  6. Implement the main function: The main function demonstrates an example usage of the drawHistogram function. It creates a vector numbers with some sample values and calls the drawHistogram function with this vector as input.

  7. Output: When you run this code, it will output a histogram representing the frequency of each number in the input vector. The number is printed followed by a colon, and the histogram is represented by asterisks (*). The number of asterisks represents the frequency of that number in the input.

I hope this explanation helps! Let me know if you have any further questions.