Search code examples
cword-countline-countcharactercount

C Programming; Word, Character and Line Count K&R 1-11


#include <stdio.h>
#define YES 0
#define NO 0

int main()
{
    int c, nl, nc, nw, tab;

    nl = 0;
    nc = 0;
    nw = 0;

    tab = NO;
    while ((c = getchar()) != EOF)
    {
        ++nc;
        if (c == '\n')
            ++nl;
        if (c == ' ' || c == '\t' || c == '\n')
            tab = NO;
        else if (tab == NO) 
        {
            tab = YES;
            ++nw;
        }
    }
    printf("NL: %d\nNC: %d\nNW: %d\n", nl, nc, nw);
}

Hey guys, new coder here. Actually, very much new, I just started a few days ago in hopes of broadening my job opportunities. Anyway, with this program, it counts every new line, word and character. For the most part, I understand what is going on but what I don't understand is the new word part. For example, at the top where we #define YES/NO, the number proceeding the word apparently does not matter? I swapped out 1 and 0 for so many other choices and yet still received the same outcome, why is that? Apologies in advance if this is a dumb question, for I myself am a dumb coder. Take care and thank you for your time!


Solution

  • Previous point:

    In C a conditional expression will evaluate to false if it is 0 and true if it is any other value, so YES can be 1, 1000, -1000, etc., as long as it is not 0 the conditional expression where it's evaluated will always be true.

    As for the question:

    For the code to work as expected YES must be 1, or, as per the explanation above, not 0.

    In

    else if (tab == NO) 
    {
        tab = YES;
        ++nw;
    }
    

    If YES is 0, tab will always be 0 and NW will not be accurate because it will count all the characters except if they are \t, or \n and this is not what program should do, NW should be the number of words.

    For instance, for this input:

    This is a word I wrote
    

    You'll have:

    NL: 1
    NC: 23
    NW: 17 
    

    When it should be:

    NL: 1
    NC: 23
    NW: 6
    

    Setting tab to 1 (YES) serves as a flag to signal that piece of code to only increment nw 1 time in case there is one of those three charaters thus counting the spaces between the words or the newline character one time only, giving you the number of words in the inputed text.