Histogram
Histogram in C
The histogram is a type of bar chart that splits a continuous measure into different bins to help analyze the distribution. Here's a step-by-step explanation of how to create a histogram in C:
- Include Necessary Libraries:
- Include the necessary libraries for input/output and mathematical operations.
Example:
c #include <stdio.h> #include <math.h>
Define the Number of Bins:
- Determine the number of bins to use for the histogram.
Example:
c #define NUM_BINS 10
Initialize Data and Bin Counts:
- Initialize an array to hold the data and another array to count the occurrences in each bin.
Example:
c int data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Example data int binCounts[NUM_BINS] = {0}; // Initialize bin counts to 0
Calculate Bin Index and Update Counts:
- Iterate through the data, calculate the bin index for each value, and update the corresponding bin count.
Example:
c for (int i = 0; i < 10; i++) { int binIndex = data[i] / (10 / NUM_BINS); // Calculate bin index binCounts[binIndex]++; // Update bin count }
Display the Histogram:
- Print the histogram using asterisks to represent the frequency in each bin.
Example:
c for (int i = 0; i < NUM_BINS; i++) { printf("%2d - %2d: ", i (10 / NUM_BINS), (i + 1) (10 / NUM_BINS) - 1); for (int j = 0; j < binCounts[i]; j++) { printf("*"); } printf("\n"); }
Complete Code Example:
Here's a complete example of a simple histogram implementation in C: ```c #include
#define NUM_BINS 10
int main() { int data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int binCounts[NUM_BINS] = {0};
for (int i = 0; i < 10; i++) { int binIndex = data[i] / (10 / NUM_BINS); binCounts[binIndex]++; } for (int i = 0; i < NUM_BINS; i++) { printf("%2d - %2d: ", i (10 / NUM_BINS), (i + 1) (10 / NUM_BINS) - 1); for (int j = 0; j < binCounts[i]; j++) { printf("*"); } printf("\n"); } return 0;
} ```
This code example demonstrates the basic steps to create a histogram in C, from initializing the data and bin counts to displaying the histogram.