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:
Include the necessary libraries: The code starts by including the
<iostream>
and<vector>
libraries, which are necessary for input/output and using vectors respectively.Define the
drawHistogram
function: ThedrawHistogram
function takes a vector of integers as input and does the following steps:- Find the maximum number: It initializes a variable
maxNumber
to 0 and iterates over the input numbers to find the maximum number. - Create a frequency array: It creates a vector
frequency
of sizemaxNumber + 1
and initializes all elements to 0. It then iterates over the input numbers again and increments the frequency count for each number. Draw the histogram: It iterates from 0 to
maxNumber
and for each numberi
, 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.Implement the
main
function: Themain
function demonstrates an example usage of thedrawHistogram
function. It creates a vectornumbers
with some sample values and calls thedrawHistogram
function with this vector as input.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.