C++ Program to Draw a Histogram
Last Updated :
05 Mar, 2023
A histogram is a graphical representation of the distribution of a set of data. It displays the data in a bar graph format, where each bar represents the count or frequency of data points falling within a specific range or bin. Histograms are commonly used in data analysis and visualization to provide insights into the distribution of data and identify trends or patterns.
In C++, histograms can be drawn using various graphical libraries such as the Simple DirectMedia Layer (SDL) or the OpenGL Utility Toolkit (GLUT), or by using ASCII characters to draw the bars in the console window. A basic histogram program can be implemented using loops and conditional statements to calculate the bin counts and draw the bars, while more advanced programs can use object-oriented programming principles and advanced graphics techniques to create interactive and customizable histograms.
Approach for creating Histogram in C++
To create a histogram in C++, the first step is to collect the data and determine the range or bins for the histogram. The data is then sorted into the appropriate bins, and the count or frequency of data points in each bin is calculated. The counts or frequencies are then represented as bars in the histogram, with the height of each bar indicating the count or frequency of data points in the corresponding bin.
The code uses a simple approach to draw a histogram using ASCII characters in the console. The main steps to implement the topic are mentioned below:
- Input: The program takes a vector of integers as input.
- Find the maximum value in the input data. This is used to determine the scaling factor for the histogram.
- Calculate the scaling factor to fit the data in the console window. This is done by dividing the maximum value in the data by the maximum height of the histogram (which is set to 20 characters) and adding 1.
- Draw the histogram. This is done by iterating over the rows of the histogram from top to bottom. For each row, the program draws the vertical axis, the data bars, and the x-axis labels. The vertical axis is drawn as a line of '-' characters, and the data bars are drawn as '#' characters if the value in the input data is greater than or equal to the current row index times the scaling factor.
- Output the histogram to the console. This is done by printing the ASCII characters to the console using the cout statement.
The code uses standard C++ libraries, including iostream and vector. It defines a drawHistogram function that takes a vector of integers as input and outputs the histogram to the console. The main function defines a sample data set and calls the drawHistogram function to draw the histogram.
Below is the implementation of the above approach:
C++
// C++ Program to print histogram
// without using external library
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Driver main
int main()
{
// Vector declared
vector<int> data = { 13, 5, 8, 9, 4, 2, 1 };
// max velue
int max_value = *max_element(data.begin(), data.end());
// Histogram
for (int i = max_value; i >= 0; --i) {
cout.width(2);
cout << i << " | ";
// Marking the values
for (int j = 0; j < data.size(); ++j) {
if (data[j] >= i) {
cout << "x ";
}
else {
cout << " ";
}
}
cout << endl;
}
cout << "---------------------------------------"
<< endl;
cout << " ";
// Data printed
for (int i = 0; i < data.size(); ++i) {
cout << data[i] << " ";
}
return 0;
}
Output13 | x
12 | x
11 | x
10 | x
9 | x x
8 | x x x
7 | x x x
6 | x x x
5 | x x x x
4 | x x x x x
3 | x x x x x
2 | x x x x x x
1 | x x x x x x x
0 | x x x x x x x
---------------------------------------
13 5 8 9 4 2 1
Explanation of the Code
This program takes a vector of integers as input and draws a histogram using ASCII characters in the console. The height of the histogram is set to a maximum of 20 characters, and the scaling factor is calculated based on the maximum value in the input data. The program then draws the vertical axis, the data bars, the horizontal axis, and the x-axis labels. Finally, the program outputs the histogram to the console.
Time Complexity:
Time Complexity = O(n * m)
- Finding the maximum value in the data: O(n), where n is the size of the data vector
- Calculating the scaling factor: O(1)
- Drawing the vertical axis: O(n)
- Drawing the data bars: O(n * m), where m is the maximum height of the histogram (20 in this case)
- Drawing the horizontal axis: O(n)
- Drawing the x-axis labels: O(n)
Therefore, the overall time complexity of the code is O(n * m), where n is the size of the input data and m is the maximum height of the histogram.
Space Complexity:
Space Complexity = O(n)
- Input data: O(n), where n is the size of the data vector
- Other variables: O(1)
Therefore, the overall space complexity of the code is O(n), where n is the size of the input data.
Note: Note that the space complexity does not take into account the space used by the console window to display the histogram, as this is outside the scope of the code. The actual space used by the program may be greater if the console window size is increased or if the program is modified to use a graphical library to display the histogram.
Conclusion
A histogram is a useful tool for visualizing the distribution of data and identifying trends and patterns. In C++, a histogram can be implemented using loops and conditional statements to calculate bin counts and drawbars, or by using graphical libraries such as SDL or GLUT to create interactive and customizable histograms. The time and space complexity of the code can be analyzed to determine the efficiency of the implementation and identify opportunities for optimization. Understanding the time and space complexity of a program is crucial in optimizing its performance and ensuring that it can handle large datasets efficiently. Overall, histograms are a powerful tool for data analysis and visualization, and their implementation in C++ is a useful skill for anyone working with data.
Similar Reads
Graph C/C++ Programs
Graph algorithms are used to solve various graph-related problems such as shortest path, MSTs, finding cycles, etc. Graph data structures are used to solve various real-world problems and these algorithms provide efficient solutions to different graph operations and functionalities. In this article,
2 min read
C++ Program For char to int Conversion
In C++, we cannot directly perform numeric operations on characters that represent numeric values. If we attempt to do so, the program will interpret the character's ASCII value instead of the numeric value it represents. We need to convert the character into an integer.Example:Input: '9'Output: 9Ex
2 min read
How to Compile a C++ Program Using GCC
In C++, the GNU Compiler Collection (GCC) is one of the most popular C/C++ compiler that is used to compile and execute the C and C++ program. In this article, we will learn how to compile a C++ program using GCC. Compiling a C++ Program Using GCC The GNU Compiler Collection (GCC) is a versatile too
2 min read
C++ Program For Hexadecimal To Decimal Conversion
The hexadecimal numbers are base 16 numbers that use 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all digits. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15). Decimal numbers are base 10 numbers with 10 symbols to represent all digits. In this article, we will l
3 min read
C++ Program For Decimal To Hexadecimal Conversion
In this article, we will learn to write a C++ program to convert a decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16. In the decimal system, we use ten digits (0 to 9) to represent a number, while in the hexadecimal system, we use sixte
3 min read
C++ Program to Implement Adjacency Matrix
An adjacency matrix is a way to represent graph data structure in C++ in the form of a two-dimensional matrix. It is a simple square matrix of size V*V, where V represents the number of vertices in the graph. Each cell of the matrix represents an edge between the row vertex and column vertex of the
4 min read
Tree C/C++ Programs
Trees are hierarchical data structures that contain nodes connected by edges. They are recursive in nature, which means that they are made up of smaller instances of themselves. Various types such as binary tree, trie, etc. have different characteristics to make them suitable for different applicati
2 min read
Menu driven program for Voting System
In this article, we will write a menu-driven program to implement the Voting System. The program must contain the following properties: Cast votes.Display the count of votes of each candidate.Display the name of the candidate who has the most votes. Approach: Follow the steps below to solve the prob
3 min read
Array C/C++ Programs
C Program to find sum of elements in a given arrayC program to find largest element in an arrayC program to multiply two matricesC/C++ Program for Given an array A[] and a number x, check for pair in A[] with sum as xC/C++ Program for Majority ElementC/C++ Program for Find the Number Occurring Odd N
6 min read
Structure of C++ Program
The C++ program is written using a specific template structure. The structure of the program written in C++ language is as follows: Documentation Section:This section comes first and is used to document the logic of the program that the programmer going to code.It can be also used to write for purpo
5 min read