Nested if Statements

   


Nested if Statements

An if-else statement lets you choose between just two different sets of actions. But sometimes, life presents us with three or more alternatives. Fortunately, the definition of an if-else statement allows you to nest if statements inside each other and thereby let a program choose between as many alternative actions as your mind can comprehend.

An if statement, as the name implies, is a statement in itself. Consequently, it can be positioned inside another if statement in the position where a statement is expected or as one of the statements in a compound statement. This is illustrated in Figure 8.5, which is based on the syntax of the if-else statement from Syntax Box 8.3.

Figure 8.5. Creating nested if statements.
graphics/08fig05.gif

Let's take a look at an example. The logic behind a simple nested if statement is illustrated by a flowchart in Figure 8.6. Notice the two decision symbols, one cascading directly from the other.

Figure 8.6. Two directly connected decision symbols.
graphics/08fig06.gif

Two decision symbols, one after the other, are a sign that nested if statements can be utilized to implement the given logic. The first decision symbol determines whether a given number is positive. If false, an appropriate message is printed. If true, the trailing decision symbol evaluates whether the number is divisible by three. If true a fitting, message is printed.

Figure 8.7 shows a code snippet containing one if statement nested inside another to implement the two cascading decision symbols of Figure 8.6.

Figure 8.7. One if statement nested inside another if statement.
graphics/08fig07.gif

Notice the braces enclosing the inner if statement in Figure 8.7. They play an important role in specifying the correct logic implemented and here is why. When you use nested if-else statements in your code, it is often questionable which else clause belongs to which if statement. Fortunately, the compiler has a very clear idea of how to match ifs with elses; the rules abided by are displayed in the following Note.

Pairing else Clauses with if Statements in Nested if-else Statements

graphics/common.gif

In an if-else statement, an else is always paired with the nearest unmatched preceding if that is located in the same block.


The logic would be significantly different if we had left out the braces in Figure 8.7; else would then have been paired with the inner if statement, as shown in Figure 8.8, because this would be the nearest unmatched preceding if and located in the same block. The latter italicized phrase is where the braces make the important difference. In Figure 8.7, they dictate the inner if statement to be in a different block than the else clause and so they prevent any pairing between the two.

Figure 8.8. One if statement nested inside another if statement no braces, correct indentation, incorrect logic.
graphics/08fig08.gif

Figure 8.8 shows an if-else statement without the braces, which no longer represents the logic of the flowchart in Figure 8.6. The indentation correctly emphasizes that the else clause now matches the inner if statement.

Had we applied the incorrect indentation shown in Figure 8.9, where the else keyword is aligned with the if keyword of the outer if statement, we could mistakenly have convinced ourselves that the else clause is paired with the outer if statement.

Figure 8.9. One if statement nested inside another if statement no braces, incorrect indentation.
graphics/08fig09.gif

The next example presents four if statements nested inside each other. They are used to accommodate a request from the financial controller of Big Bucks Bank. She believes that accounts with a balance between either $5,000 and $20,000 or between $60,000 and $75,000 hold special characteristics relevant for the cash management strategy of the bank. Therefore, the bank decides to write a program that can divide bank accounts into the following three categories:

  1. 5000 balance 20000

  2. 60000 balance 75000

  3. Neither A nor B

The flowchart of Figure 8.10 determines whether a balance belongs to category A, B, or C. Notice the four decision symbols directly connected to each other; a clear sign of the need for four if statements nested inside each other.

Figure 8.10. Determining the category of balance.
graphics/08fig10.gif

Listing 8.2 contains a prototype program that implements the logic of Figure 8.10. It simply asks the user to enter a balance and will determine to which of the three mentioned categories the balance belongs.

Listing 8.2 BalanceAssessment.cs
01: using System; 02: 03: class BalanceAssessment 04: { 05:     public static void Main() 06:     { 07:         decimal balance; 08: 09:         Console.Write("Enter balance: "); 10:         balance = Convert.ToDecimal(Console.ReadLine()); 11:         if(balance >= 5000) 12:         { 13:             if(balance <= 20000) 14:             { 15:                  //5000 <= balance <= 20000 16:                 Console.WriteLine("5000 <= balance <= 20000. Category A"); 17:             } 18:             else 19:             { 20:                 if(balance >= 60000) 21:                 { 22:                     if(balance <= 75000) 23:                          //60000 <= balance <= 75000 24:                         Console.WriteLine("60000 <= balance <= 75000. Category B"); 25:                     else 26:                          //balance > 75000 27:                         Console.WriteLine("balance > 75000. Category C"); 28:                 } 29:                 else 30:                      //20000 < balance < 60000 31:                     Console.WriteLine("20000 < balance < 60000. Category C"); 32:             } 33:         } 34:         else 35:              //balance < 5000 36:             Console.WriteLine("balance < 5000. Category C"); 37:     } 38: } 

Output sample 1:

 Enter balance: 1000<enter> balance < 5000. Category C 

Output sample 2:

 Enter balance: 7000<enter> 5000 <= balance <= 20000. Category A 

Output sample 3:

 Enter balance: 71000<enter> 60000 <= balance <= 75000. Category B 

Listing 8.2 contains four nested if statements. The first outermost if statement starts at line 11 and matches the first decision symbol in Figure 8.10. If (balance >= 5000) is false, we know that balance must be in the C category, and the program jumps to the matching else clause beginning in line 34; this is equivalent to action symbol 1 in Figure 8.10 If (balance >= 5000) is true, the category is still undecided, so we move to the second level of nested if statements in line 13. Notice that for the entire block between the braces in lines 12 and 33, we know that balance is greater than or equal to 5000. This knowledge is already helpful when combined with (balance <= 20000) of line 13. If this Boolean expression is true, we can, with certainty, conclude that 5000 >= balance >= 20000. This is equivalent to action symbol 2 of Figure 8.10. If, on the other hand, (balance <= 20000) is false, balance can still either be in the B or C category, so the flow of execution moves to the third level of if statements, commencing in line 20. Inside the block spanning lines 19 32, we can be confident that balance > 20000. Thus, if the Boolean expression (balance >= 60000) of line 20 is false, balance must be between 20000 and 60000 and belong to category C. Action symbol 3 corresponds to this situation. At line 22, we know that (balance >= 60000) is true, so if the condition (balance <= 75000) in line 22 is true, we know that 60000 <= balance <= 75000, equivalent to action symbol 4 in Figure 8.10. Finally, if (balance <= 75000) is false, balance is larger than 75000 and part of category C. This is indicated by action symbol 5 in Figure 8.10.

Whew…this was quite an intricate affair. Fortunately, there are a couple of ways by which we can simplify Listing 8.2. One, which you will meet now, provides a standardized system for writing if-else statements; the other significantly simplifies the source code by applying logical operators. The latter approach will be demonstrated in the "Logical Operators" section later in this chapter.


   


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