Sep 5, 2015

K&R : Exercise 1.11 - Testing word count

Problem Statement:

Exercise 1-11: How would you test the word count program ? What kind of input are most likey to uncover bugs if there are any ?



Solution:

For reference let me put the program already given in the book.


#include <stdio.h>

#define IN 1
#define OUT 0

int main()
{
   int c, n1, nw, nc, state;
   
   state = OUT;
   n1 = nw = nc = 0;
   
   while((c = getchar()) != EOF) {
      ++nc;
      if(c == '\n')
         ++n1;
      if(c == ' ' || c == '\n' || c == '\t')
         state = OUT;
      else if(state == OUT) {
         state = IN;
         ++nw;
      }
   }
   printf("%d  %d  %d\n", n1, nw, nc);

   return 0;
}

Testing above program would include typing a sentence, paragraphs and pressing Ctrl + d (End of File) on console/command prompt. Below are probable testing that could be done on the program.

Test 1 - No input

After you press "enter" press Ctrl + D

# ./e_1_12_word_count
0 0 0
As expected number of line is 0, number of words is 0 and number of charecters is 0.

Test 2 - One line without enter

Type one line, without pressing enter in the end press Ctrl+d


# ./e_1_12_word_count
Mary had a little lamb,0 5 23

Line is not completed with enter hence number of lines in 0, number of words is 5, number of characters is 23. Output is printed continuously on the same line, which could corrected by adding one more \n.


printf("\n%d %d %d\n", nl, nw, nc);

Test 3 - One line

Type one line, press enter in the end and then press Ctrl+d.


# ./e_1_12_word_count
Mary had a little lamb,
1 2 24
Here the program works as expected.

Test 4 - Multiple line

Type the one big paragraph and then press Ctrl+d


# ./e_1_12_word_count
Mary had a little lamb,
His fleece was white as snow,
And everywhere that Mary went,
The lamb was sure to go.
4 22 110
Here the program works also as expected.

Test 5 - One big word as input


# ./e_1_11_word_count
IamVeryBigSentenceWithoutSpace.0 1 31

Here also program works as expected, number of line is 0 (as it is not completed), number of word is 1 and number of character is 0.


Above are some examples of way it could be tested, always there would more ways of doing it.

No comments :

Post a Comment