I was working out this exercise and wanted to know if my answer is correct;
Write a program to print a histogram of the frequencies of different
characters in the input.
I have seen a couple of other answers online but they differ quite a lot to mine. Also if there are any problems in the format of my code or any improvements to be made. Any suggestions are welcome. I do understad the question requires a histogram but it’s quite easy to build one once I have the data required.
#include <stdio.h>
int main(){
int userInput;
int arrayStuff[92];
int i, j;
for(i = 0; i < 92; ++i){
arrayStuff[i] = 0;
}
while((userInput = getchar()) != '\n'){
if(userInput >= 30 && userInput <= 122){
if(userInput != '\n'){
++arrayStuff[(userInput-30)];
}
if(userInput == '\n'){
break;
}
}
}
printf("Case\t|\tOccurances\n");
for(i = 0; i < 92; ++i){
printf("%c\t|\t%d\n", (i+30), arrayStuff[i]);
}
}
Improvements I’d make:
int arrayStuff[92] = { 0 };in one go and get rid of the for loop. This is guaranteed to set all elements to 0.(sizeof arrayStuff/sizeof arrayStuff[0])instead to compute the number of elements in arrayStuff.EOFcharacter? It looks like it loops forever.int main (void)with areturn 0;. This is not C++, where an empty parameter list is equivalent to void. This is C, where an empty parameter list means “I’m an old-style K&R parameter list for an unknown but fixed number of arguments.”