MT 262 - Block 1 - Unit 3 - Looping and Branching - Page 3
fellstrider.com - the logo!
Home| OU Study Rooms | MT262 Index | Block 1 - Beginnings
 
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.

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.

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.

Home| OU Study Rooms | MT262 Index | Block 1 - Beginnings
Back to Looping and Branching Page 2
Move on to Further Considerations

Valid CSS! Valid XHTML 1.0!

Comments, suggestions, ideas to
Stuart Banner