简体   繁体   中英

Horizontal and vertical histogram of an array in C

I need to get the horizontal and vertical histogram a given array. Following is the C - code that I tried. Is there any way to improve this or any easy alternate method?

#include <stdio.h>
#define size 10
int main() {
  int array[size] = {2, 5, 7, 8, 10, 16, 7, 4, 3, 4};
  int i, j, bigCount, temp;

 /* To get Horizontal Histogram */
  for (i = 0; i < size; ++i) {
    printf("\n%3d|", i);
    for (j = 0; j < array[i]; ++j)
      printf(" #");
  }

  /* To find the biggest count */
  bigCount = array[0];
  for (i = 0; i < size; ++i)
    if(array[i] > bigCount)
      bigCount = array[i];
  temp = bigCount;
  printf("\n\n");

  /* To get Vertical Histogram */
  for (i = 0; i < bigCount; ++i) {
    printf("\n%3d|", bigCount - i);
     for (j = 0; j < size; ++j)
       if (array[j] < temp)
     printf("   ");
       else {
     printf("  #");
     --array[j];
       }
     --temp;
  }

 /* printing the x-axis */
  printf("\n    ");
  for (i = 0; i < size; ++i) 
    printf("  -", i);
  printf("\n    ");
  for (i = 0; i < size; ++i) 
    printf("%3d", i);
  printf("\n");
  return 0;

}

Nicely done. However, there are some little things which may be improved:

It seems that you have missed the x-axis on the horizontal histogram.

Also, on the line:

bigcount = array[1];

there is an off-by-one error.

The next step I would take would be to add some features to allow a user to input arbitrary data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM