Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structured Programming (Top Down Step Refinement)

Similar presentations


Presentation on theme: "Structured Programming (Top Down Step Refinement)"— 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
if (state == 0) count one more word nw++; 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);


Download ppt "Structured Programming (Top Down Step Refinement)"

Similar presentations


Ads by Google