1 / 5

Structured Programming (Top Down Step Refinement)

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:

reed
Download Presentation

Structured Programming (Top Down Step Refinement)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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)

  3. 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>

  4. 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.

  5. 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); }

More Related