Project Arithmetic

 

The while Loop

The while loop differs from the for loop in that the loop is executed an indefinite number of times. The purpose of lines IA064-IA069 below is to find out if there is a blank character in strFileName. The while loop looks like this:

 IA060:        string strFileName1 = "BullWinkle"; IA061:        int intFirstBlankCharLocation = -1; IA062:        int ww = 0; IA063:        while(strFileName1[ww] != ' ') ww++; IA064:        if(ww+1 == strFileName1.Length) IA065:        MessageBox.Show("Msg#7: There are no blank spaces in this filename."); IA066:        else IA067:        { IA068:          intFirstBlankCharLocation = ww; IA069:          MessageBox.Show("Msg#8: There is a blank space in this filename"                   + " at location '" + intFirstBlankCharLocation.ToString() + "' ."); IA070:        } 

There is something terribly wrong with this code snippet, however. What if there are no blanks in this string? What happens? The code in line IA063 faults and stops as soon as ww exceeds the length of strFileName. This is demonstrated in the demo program IfAndLoop.

A better formulation would be to change line IA063 to:

 IA063: while((strFilename1[ww] != & &) && (ww < strFileName1.Length)) ww++; 

The compound test in IA063 ” ((strFilename1[ww] != ' ') && (ww < strFileName1.Length)) ” becomes false as soon as either one or both of the substatements becomes false.

 


Unlocking Microsoft C# V 2.0 Programming Secrets
Unlocking Microsoft C# V 2.0 Programming Secrets (Wordware Applications Library)
ISBN: 1556220979
EAN: 2147483647
Year: 2005
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net