Havocado
Havocado

Reputation: 33

Generate histogram in c

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:

  1. Ask the user input and store in an array
  2. Process the array and generate the histogram array
  3. Display the histogram as stars

My code

#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");
   }
}

Input

10
1 0 6 1 5 0 7 9 0 7

Output

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] *******

Output should be:

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] *

Upvotes: 3

Views: 33866

Answers (1)

ulmer-a
ulmer-a

Reputation: 407

As @rafix07 commented, you just have to call printHistogram(results, 10) instead of printHistogram(hist, 10).

Already compiled and tested... works

Upvotes: 4

Related Questions