in the following example, I want to understand why a value of 4195520 is added to chars[2] (counting spaces).
char input;
int chars[4]; // [0] = newlines; [1] = tabs; [2] = spaces; [3] = all_else
int i, j;
printf("--\n");
printf("please enter input\n");
printf("~[enter] to end\n\n");
while ((input = getchar()) != EOF) {
if (input == '\n') {++chars[0];}
else if (input == '\t') {++chars[1];}
else if (input == ' ') {++chars[2];} // 4195520 is added (plus the amount of actual spaces), but only if I add to an array member
// if I increment an integer variable, it counts correctly
else if (input == '~') {printf("\n"); break;}
else {++chars[3];}
}
printf("--\n");
printf("the frequency of different characters\n");
printf("each dot represents one occurance\n");
for (i=0; i<=3; ++i) {
if (i == 0) {printf("newlines:\t");}
else if (i == 1) {printf("tabs:\t\t");}
else if (i == 2) {printf("spaces:\t\t");}
else if (i == 3) {printf("all else:\t");}
for (j=0; j<chars[i]; ++j) {printf(".");} // ~4.2 million dots are printed for spaces
printf("\n");
}
The solution to counting correctly is to initialize the array members to 0, but I want to understand why only whitespace and why only using an array member as a counter, increments to the number 4195520 every time.