I am reading K&R, currently on chapter 1. After reading a section and trying to solve the problems, I like to check out for other solutions online just see different methods to tackle the same problem.
Exercise 1-14 says that we need to print an histogram of the frequencies of different characters in its input. This solution I found only takes into consideration alphabet characters:
#include <stdio.h>
#define MAX 122
#define MIN 97
#define DIFF 32
int main(){
int c = EOF;
int i, j;
int array[MAX - MIN];
printf("%d ", MAX - MIN);
for (i = MIN; i <= MAX; i++){
array[i] = 0;
printf("%d ", i);
}
while ((c = getchar()) != EOF){
if (c >= MIN)
++array[c];
else {
++array[c + DIFF];
}
}
for (i = MIN; i <= MAX; i++){
printf("|%c%c|", i - DIFF, i);
for (j = 1; j <= array[i]; j++){
putchar('*');
}
putchar('\n');
}
return 0;
}
While I understand the logic behind this code, I don't understand how or why the array[] array works. When declaring the array, the size of it is 25 (MAX - MIN). This array should be indexed from 0 to 24. However during the first loop, the array is indexed using values from 97 to 122. But how is it possible to access the array if the indexing starts from a value much larger? Shouldn't the loop be
for (i = 0, i < MAX - MIN; i++)
It makes no sense to me how the array could be indexed from
array[97] ... array[122]
EDIT:
I added printf("%d ", MAX - MIN); and printf("%d ", i); in the first loop myself to try to see if it in fact was indexing the array from 97 onwards.