50 likes | 255 Views
Structured Programming (Top Down Step Refinement). Problem: To count the number of characters, the number of lines, and the number of words in a paragraph of text. Assumptions: A word is any sequence of characters that does not contain a blank, tab or newline. File buffer (text file) format:
E N D
Structured Programming(Top Down Step Refinement) Problem: To count the number of characters, the number of lines, and the number of words in a paragraph of text. Assumptions: • A word is any sequence of characters that does not contain a blank, tab or newline. • File buffer (text file) format: xxx...xxx\nxxx...xxx\nxx...xxx\nEOF • White space: blank, tab or newline Outline: 1. Declaration and initialization 2. Processing 3. Printing results
Refinement 1: 2. Processing 2.1 Read one character 2.2 While not end of file do 2.3 Action according to the input character 2.4 Read next character Variables required: c to store one character (char) nc to count the number of characters (int) nl to count the number of lines (int) nw to count the number of words (int)
Refinement 2: 2.1 c = getchar(); 2.2 while (... != EOF) 2.3 2.3.1 to count the number of characters. nc++; 2.3.2 if c = ‘\n’, to count the number of lines. nl++; 2.3.3 action for white space 2.3.4 actions for non-white space 2.4 c = getchar(); Variable required: <no extra>
Refinement 3: 2.3.3 2.3.3.1 set state = 0 (OUT) 2.3.4 2.3.4.1 if (state == 0) count one more word nw++; 2.3.4.2 set state = 1 (IN) Variable required: state the state indicates whether you are reading a word or not. (boolean, int for C) After you have done the refinements, you can start writing the code for each step.
The Final Product --- Program Code #include <stdio.h> #define IN 1 #define OUT 0 main() { int c, nl, nw, nc, state; nl = nw = nc = state = 0; while ((c = getchar()) != EOF){ nc++; if (c == ‘\n’) nl++; if (c == ‘ ‘ || c == ‘\n’ || c == ‘\t’) state = OUT; else if (state == OUT){ state = IN; nw++; } } printf(“nl=%d nw=%d nc=%d\n”, nl, nw, nc); }