Saturday 15 February 2014

arrays - What are these last lines of code doing in Exercise 1-13 of K & R's The C Programming Language? -



arrays - What are these last lines of code doing in Exercise 1-13 of K & R's The C Programming Language? -

i new programming in general, please bear lack of knowledge.

i have spent couple of hours on exercise 1-13. decided answer, found @ link https://github.com/ccpalettes/the-c-programming-language-second-edition-solutions/blob/master/chapter1/exercise%201-13/word_length.c .

because didn't want re-create sake of learning, tried understand code , remake it. (this resulted in finish copy, understand improve have otherwise.)

this have far:

#include <stdio.h> #define in 1 #define out 0 #define largest 10 main() { int c, state, l, i, j; int length[largest + 1]; (i = 0; <= largest; ++i) length[i] = 0; state = out; while ((c = getchar()) != eof) { if ((c >= 'a' && c <= 'z') || (c >= 'a' && c <= 'z')) { if (state == out) { l = 0; state = in; } ++l; } else if (state == in) { if (l <= largest) ++length[l - 1]; //minus 1 because nth term of array array[n-1] else //if (l > largest) ++length[largest]; state = out; } if (c == eof) break; } (i = 0; <= largest; ++i) { if (i != largest) //because array[10] refers 11th spot printf("\t %2d |", + 1); //plus 1 because 1st array [0] //this results in 1-10 because 0-9 plus 1 makes highest 10 else printf("\t>%2d |", largest); (j = 0; j < length[i]; ++j) putchar('x'); putchar('\n'); } homecoming 0; }

please ignore comments. meant me, explain programme myself.

i having 2 issues can't figure out, , they're driving me crazy:

the output accounts 1 word less in input, meaning "my name not bob" results in:

... 2 |xx 3 |x 4 |x ...

also, don't understand going on @ end of program. specifically, don't understand here why variable j beingness used:

(j = 0; j < length[i]; ++j) putchar('x');

thanks much help, , i'm sorry if beginner community.

well, trying sum answers since question not closed. first, need right main() line:

int main(void) { ... homecoming 0; }

the int necessary because homecoming value @ end of function, , void means function doesn't receive arguments.

i've copied code , executed on machine (ubuntu 12.04) , worked perfectly. nowadays examples generate error?

as said, j variable traverse vector. length[i] vector holds, in each position i number of words length i. instance, if position 3 has value of 4, e.g. length[3] = 4, means there 4 words length 3.

finally, if may, i'd give tip. practice choosing meaningful names variables. code linked here helped me understand programme should do. variable names such, length, or defines in, out or largest vague.

i hope gather answers until , helped more.

c arrays kernighan-and-ritchie

No comments:

Post a Comment