Looping and Branching
More on Strings
We must allow for the user to input spaces, whether it is done by error or design.
Improving the design.
- 1.1 write out "Enter a non-empty line of text."
- 1.2 read in Line
- 2.1 initialise any variables as necessary
- 2.2 Count words in Line
- 3. write out "Number of words in text is", WordCount
The technique for scanning the text will be similar but will require additional variables. The program will need to reference the Previous variable scanned with the Index variable being currently scanned. If Previous was a space and the current Index is not a space, this will signal the start of a new word. Values for Previous, Index and WordCount will then require updating.
Improved Variable Table
| Type | Identifier | Description |
| String | Line | Line of text input by user |
| Integer | WordCount | A count of the words in the input text |
| Integer | Index | For characters in the line |
| Character | Previous | Reference for the previous character of Line scanned |
Further improving the design.
- 1.1 write out "Enter a non-empty line of text."
- 1.2 read in Line
- 2.1.1 Index <— 1
- 2.1.2 Previous <— ' '
- 2.1.3 WordCount <— 0
- 2.2.1 loop while Index <= Length (Line)
- 2.2.2 if Previous = ' ' and Line [Index] ≠ ' ' then
- 2.2.3 WordCount <— WordCount + 1
- 2.2.4 ifend
- 2.2.5 Previous <— Line [Index]
- 2.2.6 Index <— Index + 1
- 2.2.7 loopend
- 3.1 write out "Number of words in text is", WordCount
What about the code?
int Index;
char Previous;
int WordCount;
AnsiString Line;
Line = ReadStringPr ("Enter a non-empty line of text: ");
Index = 1;
Previous = ' ';
WordCount = 0;
while (Index <= Length (Line))
{
if ((Previous == ' ') && (Line[Index] != ' '))
WordCount = WordCount + 1;
Previous = Line[Index];
Index = Index + 1;
}
WriteIntPrCr ("Number of words in text is ", WordCount);
This code takes no account of characters such as commas, full-stops etc. If these are entered incorrectly the program may view these as words resulting in an incorrect word count.
Comments, suggestions, ideas to
Stuart Banner
