Chapter 5. Branching

All the statements in your program execute in order. Unfortunately, that’s not very useful, unless you want your program to do exactly the same thing every time you run it. In fact, often you won’t want to execute all the code, but rather you’ll want the program to do one thing if a variable has a certain value and something different if the variable has another value. That means you need to be able to cause your program to pick and choose which statements to execute based on conditions that change as the program runs. This process is called branching, and there are two ways to accomplish it: unconditionally and conditionally.

As the name implies, unconditional branching happens every time the branch point is reached. An unconditional branch happens, for example, whenever the compiler encounters a new method call. We introduced you to methods in Chapter 1, and you’ve been using the Main( ) and WriteLine( ) methods extensively in the past three chapters. When the compiler reaches the WriteLine( ) call, the compiler stops execution in the Main( ) method and branches to the WriteLine( ) method, which exists elsewhere in the .NET Framework. When the WriteLine( ) method completes its execution—or returns—execution picks up in the original method on the line just below the branch point (the line where the WriteLine( ) method was called).

Conditional branching is more complicated. Methods can branch based on the evaluation of certain conditions that occur at runtime. For instance, you might create a branch that will calculate an employee’s federal withholding tax only when his earnings are greater than the minimum taxable by law. C# provides a number of statements that support conditional branching, such as if, else, and switch. We’ll show you how to use each of these statements later in this chapter.

A second way that methods break out of their mindless step-by-step processing of instructions is by looping. A loop causes the method to repeat a set of steps until some condition is met (for example, “Keep asking for input until the user tells you to stop or until you receive 10 values”). C# provides many statements for looping, including for, while, and do…while, which are also discussed in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset