Search code examples
cloopsinfinite-loop

My character frequency program seems to have an infinite loop


Here's my solution to exercise 1-14 of the classic, "The C Programming Language." It's supposed to return the frequencies of the characters in the input. It does that, but it keeps printing the complete list of frequencies until the compiler stops. I've tried to find the source of the infinite loop. Where is it?

#include <stdio.h>

char j;
int i;
int tally;
char input[100];
int k;

int main ()
{
for (k = 0; k < 100; k++)
{
    input[k] = getchar();
}

for (j = 0; j <= 127; j++)
{
    tally = 0;
    for (i = 0; i < 100; i++)
    {
        if (input[i] == j)
        { 
            tally++;
        }
    }
    if (tally != 0)
    {
        printf ("%c : %d times\n", j, tally);
    }
}
return 0;
}

Solution

  • The problem is with your variable j, which has type char:

    for (j = 0 ; j <= 127 ; j++)
    

    On systems where char is signed, max value of char is 127, meaning that j <= 127 condition is always true.

    Although you can fix this problem by declaring j as unsigned char, there is a better approach to counting characters: make an array of 128 counters, and walk through the input[] once:

    unsigned char input[100];
    int tally[128] = {0};
    for (int i = 0 ; i < 100 ; i++) {
        if (input[i] < 128) {
            tally[input[i]]++;
        }
    }
    for (int c = 0 ; c != 128 ; c++) {
        if (tally[c] != 0) {
            printf("%c : %d times\n", c, tally[c]);
        }
    }