The program accepts an array as input and prints a histogram. It uses srand() method for random data creation ranging from 0 to 20 elements.
We need to generate a frequency array for 100 numbers between 0-19. Further, we need to create, add data and print a corresponding histogram for same.
Program to Print Histogram in C
Program:
/****************************************************************************** Program to print histogram from given array in C *******************************************************************************/ #include<stdio.h> #include <stdlib.h> #include<time.h> int main () { int arr[100], i, barSize, p, count; // Variables that are being used for printing histogram int firstBar = 0, secBar = 0, thirdBar = 0, fourthBar = 0, lowerRange = 0, upperRange = 5; // srand for creating random values between 0 to 20 srand (time (0)); for (i = 0; i < 100; i++){ arr[i] = rand () % 20; } // printing autogenerated array elements on output screen printf ("Array values for the histogram :: \n"); for (i = 0; i < 100; i++){ printf ("%d ", arr[i]); } // printing histogram in C by spliting bar in intervals of 5 i.e 0-5, 5-10 for (i = 0; i < 100; i++){ if (arr[i] < 5){ firstBar = firstBar + 1; } else if ((arr[i] < 10) && (arr[i] > 5)){ secBar = secBar + 1; } else if ((arr[i] < 15) && (arr[i] > 10)){ thirdBar = thirdBar + 1; } else{ fourthBar = fourthBar + 1; } } // Printing histogram in C printf ("\n\n*************** HISTOGRAM ***************\n\n"); i = 1; barSize = firstBar; while (i <= 4){ printf ("\n |\n%2d-%2d|", lowerRange, upperRange); p = 1; while (p <= barSize){ printf ("*"); p++; } printf ("\n |\n"); if (i == 2) barSize = secBar; if (i == 3) barSize = thirdBar; if (i == 4) barSize = fourthBar; lowerRange = lowerRange + 5; upperRange = upperRange + 5; i++; } return 0; }
Output:
Random data inputs are generated first:-
Array values for the histogram :: 6 18 0 9 16 16 17 6 3 10 6 18 13 6 5 15 7 5 17 9 15 6 16 7 15 14 0 0 12 8 12 18 18 12 7 14 0 17 0 15 7 19 13 12 5 10 0 4 15 17 14 2 15 10 9 10 17 2 2 1 2 14 0 0 18 19 14 19 16 6 14 15 5 8 0 2 10 0 19 6 17 13 0 13 15 2 15 4 4 18 6 6 4 18 6 3 9 12 14 18
Plotted to Histogram:
*************** HISTOGRAM *************** | 0- 5|************************ | | 5-10|************************ | | 10-15|******************** | | 15-20|**************** |
Explanation:
- We have generated frequency data, with values ranging from 0 to 19
- To create a histogram, we have used intervals 0-5,5- 10, 10-15, 15-20 with 5 class size
- In order to create 4 bars, we have used 4 variables named, firstBar, secBar, thirdBar, and fourthBar
- While iterating frequency data, if the value lies between 0 to 5, count it as 1 and add it to the first bar
- Similarly, if it ranges from 5 to 10, then add 1 to secBar variable
- Lastly, we have printed the histogram on the output screen