Swith and Iteration C Sharp

switch statement:

Nested if statements are hard to read, hard to get right, and hard to debug. When you have a complex set of choices to make, the switch statement is a more powerful alternative. The logic of a switch statement is this: "pick a matching value and act accordingly."

The expression you are "switching on" is put in parentheses in the head of the switch statement. Each case statement compares a constant value with the expression. The constant expression can be a literal, symbolic, or enumerated constant.

The compiler starts with the first case statement and works its way down the list, looking for a value that matches the expression. If a case is matched, the statement (or block of statements) associated with that case is executed.

The case block must end with a jump statement. Typically, the jump statement is break, which abruptly ends the entire switch statement. When you execute a break in a switch statement, execution continues after the closing brace of the switch statement.

The statements between the case statement and the break are executed in series. You can have more than one statement here without braces; in effect the case statement and the closing break statement act as the braces.If the user does not choose one of the values that correspond to a case statement, the default statements will execute.

Falling Through and Jumping to Cases :

If two cases will execute the same code, you can create what's known as a "fall through" case, grouping the case statements together with the same code, as shown here:

In this example, if the user chooses either CompassionateRepublican or Republican, the same set of statements will be executed.

Note that you can only fall through if the first case executes no code. In this example, the first case, CompassionateRepublican, meets that criteria. Thus, you can fall through to the second case.

If, however, you want to execute a statement with one case and then fall through to the next, you must use the goto keyword to jump to the next case you want to execute.

For example, if you create a NewLeft party, you might want the NewLeft voting choice to print a message and then fall through to Democrat (that is, continue on with the statements in the Democrat case). You might (incorrectly) try writing the following:

Switch on string Statements:

C# also offers the ability to switch on a string.

Iteration Statements :

There are many situations in which you will want to do the same thing again and again, perhaps slightly changing a value each time you repeat the action. This is called iteration or looping. Typically, you'll iterate (or loop) over a set of items, taking the same action on each. This is the programming equivalent of an assembly line. On an assembly line, you might take a hundred car bodies and put a windshield on each one as it comes by. In an iterative program, you might work your way through a collection of text boxes on a form, retrieving the value from each in turn and using those values to update a database.

C# provides an extensive suite of iteration statements, including for and while, and also do...while and foreach loops. You can also create a loop by using the goto statement. The remainder of this chapter considers the use of goto, for, while, and do...while.

Creating Loops with goto:

The goto statement was used previously as an unconditional branch in a switch statement. Its more common usage, however, is to create a loop. In fact, the goto statement is the seed from which all other looping statements have been germinated. Unfortunately, it is a semolina seed, producer of spaghetti code and endless confusion.

Programs that use goto statements outside of switch blocks jump around a great deal. Goto can cause your method to loop back and forth in ways that are difficult to follow.

If you were to try to draw the flow of control in a program that makes extensive use of goto statements, the resulting morass of intersecting and overlapping lines might look like a plate of spaghetti — hence the term "spaghetti code." Spaghetti code is a contemptuous epithet; no one wants to write spaghetti code.

Most experienced programmers properly shun the goto statement, but in the interest of completeness, here's how you use it:

  1. Create a label.

  2. goto that label.

The label is an identifier followed by a colon. You place the label in your code, and then you use the goto keyword to jump to that label.

The while Loop :

The semantics of the while loop are "while this condition is true, do this work." The syntax is:

while (boolean expression) statement

As usual, a Boolean expression is any statement that evaluates to true or false. The statement executed within a while statement can of course be a block of statements within braces.The while statement is nicely self-contained, and it reads like an English sentence: "while counterVariable is less than 10, print this message and increment counterVariable."

Notice that the while loop tests the value of counterVariable before entering the loop. This ensures that the loop will not run if the condition tested is false; thus if counterVariable is initialized to 11, the loop will never run.

The do . . . while Loop:

There are times when a while loop might not serve your purpose. In certain situations, you might want to reverse the semantics from "run while this is true" to the subtly different "do this, while this condition remains true." In other words, take the action, and then, after the action is completed, check the condition. Such a loop will always run at least once.

To ensure that the action is taken before the condition is tested, use a do...while loop:

do statement while (boolean-expression);

The syntax is to write the keyword do, followed by your statement (or block), the while keyword, and the condition to test in parentheses. End the statement with a semicolon.

The for Loop :

You write a for loop with the keyword for, followed by the for header, using the syntax:

The first part of the header is the initializers, in which you initialize a variable. The second part is the Boolean expression to test. The third part is the iterator, in which you update the value of the counter variable. All of this is enclosed in parentheses.

No comments:

Post a Comment