Thread: Exercise 1-13 in K&M

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    13

    Exercise 1-13 in K&M

    Hey guys. Have been self teaching myself programming and got stuck on another problem. For problem 1-13 in the K&M, it asks for a program that makes a histogram of lengths of words. I figured that was a too too difficult and decided instead to just make a program that counts the numbers of words of different lengths, and to make it even easier I decided to just limit it to 10. Yet I can't even get that to work =\

    Code:
    #include <stdio.h>
    
    main(){
    
    #define IN 1
    #define OUT 0
    
    int c, i, j, state;
    int word[10];
    
    i = 0;
    state = OUT;
    
    for (j=0;j<=9;++j)
    word[j]=0;
    
    
    while ((c = getchar()) != EOF)
    {
        if ((c == ' '|| c == '\b'|| c == '\n') && state == IN )
        {
        state = OUT;
        ++word[i - '1'];
        i = 0;
        }
        else if ((c==' '|| c=='\b'|| c=='\n') && state == OUT);
    
        else
        {
        ++i;
        state == IN;
    }
    }
    
    printf("The number of words length 1 2 3 4 5 6 7 8 9 10 is\n\t\t\t\t");
    
    for (j=0;j<=9;++j)
    printf("%d ", word[j]);
    }
    when I print it just prints out all 0's. Not quite sure what I'm doing wrong. Thanks in advance.

  2. #2
    Registered User
    Join Date
    Mar 2010
    Posts
    583
    It's mostly okay -- you just have a couple of mistakes. The logic of the code, which is the difficult bit, looks to be fine.

    Code:
    else
        {
            ++i;
            state == IN;
        }
    Looks like a typo I think you wanted '=' (assignment) not '==' (equality).

    Code:
        ++word[i - '1'];
    '1' in single quotes is the character "1", not the number 1. This line will subtract the character encoding for 1 from i!

    Finally,

    Code:
        else if ((c==' '|| c=='\b'|| c=='\n') && state == OUT);
    Nothing wrong with this, it's legal C and will work, but I don't really like the style. I know it's exactly the same but I'd write:
    Code:
        else if ((c==' '|| c=='\b'|| c=='\n') && state == OUT)
            ; // do nothing

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    13
    Ah. Yeah that got it. Thanks a bunch smokeyangel

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. exercise help
    By ali.franco95 in forum C Programming
    Replies: 2
    Last Post: 09-24-2011, 11:02 AM
  2. exercise help
    By ali.franco95 in forum C Programming
    Replies: 3
    Last Post: 09-09-2011, 05:59 AM
  3. Exercise C, or for, or while or do while
    By vanina_18 in forum C Programming
    Replies: 1
    Last Post: 06-15-2010, 03:20 PM
  4. An exercise from K&R
    By GL.Sam in forum C Programming
    Replies: 4
    Last Post: 05-07-2010, 09:31 AM
  5. Help with K&R Exercise 1.13
    By Yannis in forum C Programming
    Replies: 2
    Last Post: 09-21-2003, 02:51 PM