Looping


Looping provides the ability to perform a task one or more times until a larger task is complete. This is a reoccurring theme in development. Tasks such as computing the total payroll for a division within a company require looping through each employee's salary information and summing the total value. Rather than hard-coding the necessary statements for N number of employees, a loop can be used to process each employee until all employee salary information has been processed.

C# offers various looping constructs that can be used to perform repetitive tasks. Each has benefits and a time and place for its use. There is no such thing as one-size-fits-all, and this is the reason why there are so many ways to accomplish a particular task.

The for Loop

The for statement is the most common looping construct and is found in most languages. Although its syntax differs from language to language, its overall purpose is still the same: to iterate over a set of statements for a fixed number of cycles. At least, that's the way it should be used. The for statement has the following syntax:

 for( initial value; test; increment/decrement value )   single-statement; 

or

 for( initial value; test; increment/decrement value ) {   One or more statements; } 

The for statement controls the very next C# statement. For multiple statements to be under control of the for statement, it's necessary to use code blocks { } to enclose the statements.

Using the for Statement

The for loop is basically a block of code that executes a set number of times, performing some repetitive task, enabling the programmer to write the code only once even though it executes multiple times. Loops are at the core of the set of skills required of every programming.

Using the for statement to accomplish a repetitive task is as simple as the following:

 for( int i = 0; i < 50; i++ )   Console.WriteLine( "I will not chew gum in school"); 

Notice that the value i goes from 0 to less than 50. This equates to the loop executing 50 timesthe range from 0 to 49, inclusive. This is a common place for error because it is easy to test for i <= 50; which, of course, would result in 51 executions of the loop rather than 50 as intended.

The real value of the for statement is the ability to loop though items in an array or collection. Because of this, we'll put off further exploration of the for statement until Chapter 5, "Arrays and Collections."

The foreach Statement

The foreach statement is new to modern languages. It allows for traversal over containers that implement the IEnumerable interface and provide an enumerator that implements the IEnumerator interface. That might seem confusing, but it will become clearer in Chapter 5. Only in the context of Chapter 5 will the foreach statement make more sense. However, just to give you something to ponder, the syntax looks like this:

 foreach( Type T in myCollection ) {   T is now in scope for use and represents the current item } 

The while Loop

Like the for statement, the while statement allows for one or more statements to be executed until a test condition evaluates to true. Unlike the for statement, the purpose of the while statement is to execute for an unspecified number of iterations. This comes in handy for operations such as reading data from a database where the number of rows returned is not known at the time of processing or when parsing a string into tokens. The format of the while statement is very simple. The syntax is

 while( expression ) { statement1; statement2; . . . statementN; } 

Like the for statement, the while statement controls the next C# statement. To control a group of statements, the statements must be grouped within the code block { }.

To demonstrate the basic use of the while statement, Listing 3.6 creates a very simple calculator. This calculator will handle expressions only in the format of "digit operator digit," where the operator is one of the following: +, -, *, /.

Listing 3.6. Using the while Statement to Parse an Input String
 using System; namespace WhileStatement {     class Class1 {         /// <summary>         ///Evaluates a simple math expression such as 25 + 30         ///Does not handle complex expressions ///like 20 + 30 * 2 - 5.         /// </summary>         [STAThread]         static void Main(string[] args) {             Console.Write( "Enter a simple math expression: " );             string expression = Console.ReadLine( );             float result        = 0;             int idx                = 0;             //eat white space             while( char.IsWhiteSpace( expression[ idx ] ) )                 idx++;             //parse the 1st digit             string digit    = string.Empty;             char c = expression[ idx++ ];             while( char.IsDigit( c ) ) {                 digit = digit + c;                 c = expression[ idx++ ];             }             int digit1 = Int32.Parse( digit );             //eat white space             while( char.IsWhiteSpace( expression[ idx ] ) )                 idx++;             //parse the operator             char op = expression[idx++];             //eat white space             while( char.IsWhiteSpace( expression[ idx ] ) )                 idx++;             //parse the 2nd digit             digit    = string.Empty;             c = expression[ idx++ ];             while( char.IsDigit( c ) ) {                 digit = digit + c;                 if( idx < expression.Length )                     c = expression[ idx++ ];                 else                     break;    //exits the while loop             }             int digit2 = Int32.Parse( digit );             //what was the operator?             switch( op ) {                 case '+':                     result = (float)(digit1 + digit2);                     break;                 case '-':                     result = (float)(digit1 + digit2);                     break;                 case '*':                     result = (float)(digit1 * digit2);                     break;                 case '/':                     result = (float)digit1 / (float)digit2;                     break;             }             //display the result             Console.WriteLine( "The result of " + expression                + " is " + result.ToString( ) );         }     } } 

Listing 3.5 shows the basic use of the while statement to perform parsing of a string into tokens: namely, digits and the operator. Notice line 50 and the use of the break statement. The break statement is not only used within the switch control statement, but also can be used within the for and while statements to exit the loop. The counterpart to the break statement is the continue statement.

The continue statement skips the remaining body of the loop statement and transfers control back to the next iteration of the enclosing loop statement. It's worth noting that the continue statement is rarely used, and chances are that you will find a use for it only once every few years.

The do..while Loop

The final looping control structure is the do..while statement. The do..while statement works in the same fashion as the while statement, with one key difference: The do..while statement is guaranteed to execute at least once. This is due to the fact that the control expression is evaluated at the end of each iteration rather than at the start of each iteration. The while statement, on the other hand, evaluates the control expression before proceeding and therefore might not execute at all.

The syntax for the do..while statement is merely an upside-down while statement as such:

 do {   statement1;   statement2;   statement3; } while( control-expression ); 

To contrast the difference between the two statements, create a new console application and copy the code statements in Listing 3.7 into the Main method.

Listing 3.7. Difference Between while and do..while
 do {   Console.WriteLine( "do..while executes at least once" ); } while( false ); while( false ) {   Console.WriteLine( "while statement does not even have to execute" ); } 



    Visual C#. NET 2003 Unleashed
    Visual C#. NET 2003 Unleashed
    ISBN: 672326760
    EAN: N/A
    Year: 2003
    Pages: 316

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