Branching with the if Statement

   


Branching with the if Statement

The if statement comes in different varieties. We will first look at the very basic if statement version (termed the simple if statement) with which you are already familiar.

The Simple if Statement

The syntax of the simple if statement is displayed in Syntax Box 8.1.

Syntax Box 8.1 Simple if-Statement

 Simple_if-statement::=                        if(<Boolean_expression>)                            <Statement>; 

Note

graphics/common.gif

Recall from Chapter 6 that a Boolean expression is always evaluated to one of the two bool values true and false.


The <Statement> immediately after the Boolean expression will only be executed if the Boolean expression of the if statement is evaluated to true.

For example, the Big Bucks Bank offers an account to its customers with the following specifications:

The account only pays interest if the balance is over $1000, in which case it pays 10% of the current balance.

We can express these conditions in a flowchart, as illustrated in Figure 8.1.

Figure 8.1. Calculating the interest for the account of the Big Bucks Bank.
graphics/08fig01.gif

The rules of the flowchart can be written in C# by using the simple if statement:

 if (balance > 1000)      balance = balance + (0.1 * balance);    //executed only if balance > 1000 

which will only execute the second line if the Boolean expression balance > 1000 is true.

Note

graphics/common.gif

A Boolean expression must be enclosed by parentheses when it is part of an if statement, as shown in Syntax Box 8.1. This is common for all branching and looping statements. However, Boolean expressions separate from these constructs do not have this requirement.


Note

graphics/tnt.gif

C# allows you to include so-called empty statements, also called null statements, in your code. An empty statement, as the name implies, does nothing. Recall that every statement must end with a semicolon. An empty statement is simply specified by a single semicolon (here often termed the do-nothing operator) located in a position where a statement is expected. For example, the semicolon of the second line in the following code snippet terminates an empty statement, whereas the two semicolons in the first and third lines terminate statements that both perform a computation:

 distance = speed * time; ; totalTime = time1 + time2; 

What's the point of having a statement that does nothing? Well, sometimes a statement is required in the source code, but no operation is needed. However, this is not the main issue here. The important part is as follows.

The existence of the empty statement can lead to well-hidden bugs if mistakenly positioned after the rightmost parentheses enclosing the Boolean expression of an if statement. Let's use the already mentioned bank account example to illustrate. If, by mistake, you put a semicolon in the first line of the if statement as indicated in Figure 8.2, it would create an empty statement here, because a statement is expected in this position. The C# compiler would now regard the empty statement as the statement to execute whenever balance > 1000 is true and would not consider the second line to be part of the if statement anymore. It would merely be interpreted as the next statement after the if statement. As a result, the second line would always be executed.

Figure 8.2. Inserting an empty statement in an if statement by mistake. Programmers view.
graphics/08fig02.gif

Recall that the compiler, as indicated in Figure 8.2, ignores indentation. Incorrect indentation can easily fool us into believing that an if statement represents the correct logic when this is not the case. For that reason, it is often difficult to spot errors produced by the inadvertent use of the empty statement. If we write the if-statement of Figure 8.2 according to the compiler's interpretation of the statement, it becomes much easier to spot the problem. To achieve this effect, we simply need to move the semicolon one line down and indent it, as shown in Figure 8.3.

Figure 8.3. Inserting an empty statement in an if statement by mistake. Compilers view.
graphics/08fig03.gif

In most cases, the C# compiler will detect the empty statement after an if statement and issue a warning, which might look like

 EmptyStatement.cs(8,20): warning CS0642: Possible mistaken null statement 


Compound Statements

The previous simple if statement only allowed us to execute one statement in case of a true Boolean expression. What if we need to execute more than one statement? For example, we might want the computer to print a message every time interest is added to our account as well as adding the interest. C# accommodates for this requirement by letting us substitute the single <statement> of Syntax Box 8.1 with a compound statement. The latter is defined in Syntax Box 8.2.

Syntax Box 8.2 The Compound Statement

A compound statement is simply another term for the familiar block of statements that you have seen in many previous examples.

 Compound_statement::= {     <Statements> } 

This allows us to write


graphics/08infig01.gif

which adds the interest and prints the message if the Boolean expression is true. If the Boolean expression is false, none of the statements of the compound statement will be executed.

The Optional else Clause

Big Bucks Bank offers another bank account to its customers with the following interest rates:

If the balance is positive, pay 10% interest of the balance to the customer; otherwise, charge the customer 15% interest of the balance.

This interest payment rule is illustrated by a flowchart in Figure 8.4.

Figure 8.4. Choosing among two alternative actions.
graphics/08fig04.gif

To implement this flowchart, we need to somehow express in C# that a choice is made among two alternative actions. This can be accomplished by extending the if statement with the optional else clause, as shown in Syntax Box 8.3.

Syntax Box 8.3 if-else Statement

 if-else_statement::= if(<Boolean_expression>)       <Statement1>; | <Compound_statement1> [else       <Statement2>; | <Compound_statement2>] 

Notes:

  • <Statement1>; | <Compound_statement1> is only executed if <Boolean_expression> is true.

  • <Statement2>; | <Compound_statement2> is only executed if <Boolean_expression> is false.

  • The [symbol in front of else and the ] symbol after <Compound_statement2> symbolize that everything in between these two symbols is optional, as usual.

  • Recall that the vertical line |, as in <Statement>; | <Compound_statement>, is surrounded by alternatives (see Syntax Box 6.1 of Chapter 6). In this case, it specifies that we can either use a <Statement> or a <Compound_statement>.

The flowchart in Figure 8.4 can then be expressed in C# as


graphics/08infig02.gif

Note

graphics/common.gif

The mathematical symbol for greater-than-or-equal-to is but does not exist on a conventional computer keyboard. In C#, the equivalent to was therefore chosen to be >=. The comparison operators != and <= were chosen for that same reason.


According to Syntax Box 8.3, it is possible to substitute the single statements by compound statements. This has been put into practice in lines 13 22 of Listing 8.1, which implements the bank account rule of Figure 8.4, along with a simple user interface.

Listing 8.1 BankAccount.cs
01: using System; 02: 03: class BankAccount 04: { 05:     public static void Main() 06:     { 07:         const decimal InterestRatePaid = 0.1m; 08:         const decimal InterestRateCharged = 0.15m; 09:         decimal balance; 10: 11:         Console.Write("Please enter account balance: "); 12:         balance = Convert.ToDecimal(Console.ReadLine()); 13:         if(balance >= 0) 14:         { 15:             Console.WriteLine("Interest paid: {0,13:C} ", (balance *  graphics/ccc.gifInterestRatePaid)); 16:             balance = balance + (balance * InterestRatePaid); 17:         } 18:         else 19:         { 20:             Console.WriteLine("Interest charged: {0,10:C} ", -(balance *  graphics/ccc.gifInterestRateCharged)); 21:             balance = balance + (balance * InterestRateCharged); 22:         } 23:         Console.WriteLine("New balance: {0,15:C} ", balance); 24:     } 25: }     

Sample 1 positive balance:

 Please enter account balance: 1000<enter> Interest paid:       $100.00 New balance:       $1,100.00 

Sample 2 negative balance:

 Please enter account balance: -1000<enter> Interest charged:    $150.00 New balance:      $1,1500.00 

Lines 15 and 16 will only be executed if balance >= 0 (line 13) is true; otherwise, lines 20 and 21 will be executed.

Line 23 is the next statement after the if-else statement, so it will always be executed.

Indentation Style

graphics/bulb.gif

Notice how the if-else statement in lines 13 22 of Listing 8.1 applies a certain indentation style. It aligns the opening and closing braces under the if keyword and indents the statements as follows:

 if (<Boolean_expression>) {     <statements> } 

There are many possible indentation styles, but together with the style of Listing 8.1, two other variations seem to dominate in the programming community:

The braces and the statements are all indented:

 if (<Boolean_expression>)     {         <statements>     } 

The opening brace is positioned in the same line after the (<Boolean_expression>), the <statements> are indented, and the closing brace is aligned under if

 if (<Boolean_expression>) {     <statements> } 

Every different style shown here has pros and cons, so you are free to choose your preferred style. The most important thing to remember is to be consistent always use the same style throughout a software project.



   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

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