I am stuck with creating this histogram in C. The thing is that the assignment is to count how often every user input occurs.
For: 1 0 6 1 5 0 7 9 0 7 --> there is 3x 0, 2x 1, etc.
Then, the occurrence has to be converted to stars instead of the number of occurrences. I think I covered the 1st and 3rd steps, but I struggle with converting the number to stars. Do I have to make a new loop, or do I use the current nested loops? I will be forever grateful to whoever can provide me some insights.
So my exercise is:
#include <stdio.h>
void printHistogram ( int *hist, int n );
int main() {
int i, j;
int inputValue;
printf("Input the amount of values: \n");
scanf("%d", &inputValue);
int hist[inputValue];
printf("Input the values between 0 and 9 (separated by space): \n");
for (i = 0; i < inputValue; ++i) {
scanf("%d", &hist[i]);
}
int results[10] = {0};
// Processing data to compute histogram, see 5.17
for (i = 0; i < 10; ++i) {
for(j = 0; j < inputValue; j++) {
if ( hist[j] == i){
results[i]++;
}
}
}
printf("\n");
printHistogram(hist, 10);
return 0;
}
void printHistogram(int *hist, int n) {
int i, j;
for (i = 0; i < n; i++) {
printf("[%d] ", i);
for ( j = 0; j < hist[i]; ++j) {
printf("*");
}
printf("\n");
}
}
10
1 0 6 1 5 0 7 9 0 7
Input the amount of values:
Input the values between 0 and 9 (separated by space):
[0] *
[1]
[2] ******
[3] *
[4] *****
[5]
[6] *******
[7] *********
[8]
[9] *******
Input the amount of values: 10
Input the values between 0 and 9 (separated by space):
[0] ***
[1] **
[2]
[3]
[4]
[5] *
[6] *
[7] **
[8]
[9] *
As @rafix07 commented, you just have to call printHistogram(results, 10) instead of printHistogram(hist, 10).
Already compiled and tested... works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With