Chapter 4 Readings: 4.3 Nested Decision Structures

Nested Decision Structures

Core Concepts

A control structure determines the order in which a set of statements executes. Computer programs are routinely designed by combining different control structures, such as sequence structures and decision structures.

A nested decision structure occurs when a decision structure is placed inside another decision structure. This design is necessary when a program must test more than one condition before deciding which action to execute.

Execution Combination Example
  1. Initial Sequence Structure:

    • Step 1: Go to the window

    • Step 2: Read thermometer

  2. Decision Structure:

    • Condition tested: Cold outside

    • If true: Execute action "Wear a coat".

    • If false: Skip directly to the next sequence structure.

  3. Subsequent Sequence Structure:

    • Step 1: Open the door

    • Step 2: Go outside

Multi-Condition Logic: Loan Qualification Example

To qualify for a bank loan, a customer must satisfy two conditions simultaneously:

  1. Salary Condition: Annual salary must be at least 40,00040,000 (salary≥40000\text{salary} \ge 40000).

  2. Employment Duration Condition: Must have been employed at their current job for at least 22 years (yearsOnJob≥2\text{yearsOnJob} \ge 2).

Algorithm Execution Flow
  • First, test the outer Boolean expression: salary≥40000\text{salary} \ge 40000.

    • If false: Execution bypasses all further tests. The customer does not qualify for the loan.

    • If true: Execution proceeds to the inner nested decision structure.

  • Second, test the nested Boolean expression: yearsOnJob≥2\text{yearsOnJob} \ge 2.

    • If true: The customer satisfies both conditions and qualifies for the loan.

    • If false: The customer does not qualify for the loan.

Loan Qualifier Application (Tutorial 4-3)

Application Overview

The Loan Qualifier application determines loan eligibility using nested decision structures. Located in the Chap04 folder of the Student Sample Programs, the project contains a form named Form1.

Development Steps
  1. Start Environment: Launch Visual Studio and open the project named Loan Qualifier from the Chap04 folder.

  2. Open Design View: Open Form1 in the Designer view to inspect form controls.

  3. Implement Check Qualifications Button: Double-click the checkButton control to auto-generate the checkButton_Click event handler shell, then populate lines 22–62.

  4. Implement Clear Button: Double-click the clearButton control to generate the clearButton_Click event handler shell, then populate lines 67–73.

  5. Implement Exit Button: Double-click the exitButton control to generate the exitButton_Click event handler shell, then populate lines 78–79.

  6. Testing and Verification:

    • Test 1: Input Salary = 45000, Years on Job = 1. Click checkButton.

      • Output: "Minimum years at current job not met."

    • Test 2: Click Clear. Input Salary = 35000, Years on Job = 5. Click checkButton.

      • Output: "Minimum salary requirement not met."

    • Test 3: Click Clear. Input Salary = 45000, Years on Job = 5. Click checkButton.

      • Output: "You qualify for the loan."

    • Exit: Click Exit button; the form closes via this.Close().

Program 4-3: Complete Form1 Source Code Breakdown
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 
11 namespace Loan_Qualifier
12 {
13     public partial class Form1 : Form
14     {
15         public Form1()
16         {
17             InitializeComponent();
18         }
19 
20         private void checkButton_Click(object sender, EventArgs e)
21         {
22             try
23             {
24                 // Names constants
25                 const decimal MINIMUM_SALARY = 40000m;
26                 const int MINIMUM_YEARS_ON_JOB = 2;
27 
28                 // Local variables
29                 decimal salary;
30                 int yearsOnJob;
31 
32                 // Get the salary and years on the job.
33                 salary = decimal.Parse(salaryTextBox.Text);
34                 yearsOnJob = int.Parse(yearsTextBox.Text);
35 
36                 // Determine whether the user qualifies.
37                 if (salary >= MINIMUM_SALARY)
38                 {
39                     if (yearsOnJob >= MINIMUM_YEARS_ON_JOB)
40                     {
41                         // The user qualifies.
42                         decisionLabel.Text = "You qualify for the loan.";
43                     }
44                     else
45                     {
46                         // The user does not qualify.
47                         decisionLabel.Text = "Minimum years at current " +
48                             "job not met.";
49                     }
50                 }
51                 else
52                 {
53                     // The user does not qualify.
54                     decisionLabel.Text = "Minimum salary requirement " +
55                         "not met.";
56                 }
57             }
58             catch (Exception ex)
59             {
60                 // Display an error message.
61                 MessageBox.Show(ex.Message);
62             }
63         }
64 
65         private void clearButton_Click(object sender, EventArgs e)
66         {
67             // Clear the TextBoxes and the decisionLabel.
68             salaryTextBox.Text = "";
69             yearsTextBox.Text = "";
70             decisionLabel.Text = "";
71 
72             // Reset the focus.
73             salaryTextBox.Focus();
74         }
75 
76         private void exitButton_Click(object sender, EventArgs e)
77         {
78             // Close the form.
79             this.Close();
80         }
81     }
82 }
Line-by-Line Code Explanation
  • Line 22: Begins try-catch construct spanning lines 22–62 (try block lines 24–56, catch block lines 60–61). Bypasses standard runtime crashes if invalid string inputs are provided, routing execution directly to line 61 to display ex.Message inside a MessageBox.

  • Lines 25–26: Named Constants:

    • const decimal MINIMUM_SALARY = 40000m;: Stores the threshold salary value of 40,00040,000.

    • const int MINIMUM_YEARS_ON_JOB = 2;: Stores the threshold job tenure of 22 years.

  • Lines 29–30: Variable declarations: decimal salary and int yearsOnJob.

  • Lines 33–34: String parsing from controls salaryTextBox.Text and yearsTextBox.Text into typed numeric variables.

  • Lines 37–56: Nested decision logic:

    • Line 37 checks outer expression salary >= MINIMUM_SALARY. If false, control transfers to outer else at line 51, assigning "Minimum salary requirement not met." to decisionLabel.Text (lines 54–55).

    • If true, control passes to line 39 to evaluate yearsOnJob >= MINIMUM_YEARS_ON_JOB.

    • Line 42 executes if both conditions are true: decisionLabel.Text = "You qualify for the loan.";.

    • Line 44 (else of inner structure) executes if inner expression fails: decisionLabel.Text = "Minimum years at current job not met."; (lines 47–48).

  • Lines 65–74: clearButton_Click handler resets salaryTextBox.Text, yearsTextBox.Text, and decisionLabel.Text to empty strings "", then invokes salaryTextBox.Focus() to place the input cursor back into the salary text field.

  • Lines 76–80: exitButton_Click handler executes this.Close() to terminate and dismiss the form.

Code Formatting and Structural Alignment

Indentation Principles

Proper alignment and indentation in nested decision structures are critical for debugging and readability, though not syntactically enforced by the C# compiler.

Unindented vs. Indented Code Comparison

Unindented code is logically identical to properly indented code, but visually obscure:

// Poorly formatted equivalent code
if (salary >= MINIMUM_SALARY)
{
if (yearsOnJob >= MINIMUM_YEARS_ON_JOB)
{
// The user qualifies.
decisionLabel.Text = "You qualify for the loan.";
}
else
{
// The user does not qualify.
decisionLabel.Text = "Minimum years at current " +
"job not met.";
}
}
else
{
// The user does not qualify.
decisionLabel.Text = "Minimum salary requirement " +
"not met.";
}

Visual Studio automatically formats, aligns, and indents nested decision structures to explicitly show parent-child relationships between specific if and else clauses.

Testing a Series of Conditions

The Grader Application

When a program must evaluate multiple sequential conditions to determine a single outcome, nested decision structures can be chained.

The Grader application (found in Chap04) prompts the user to enter a numeric test score into testScoreTextBox and click determineGradeButton. The corresponding letter grade is printed in gradeLabel.

10-Point Grading Scale

Test Score Range

Grade

90 and above

A

80–89

B

70–79

C

60–69

D

Below 60

F

Sequential Decision Logic Flow
  1. If testScore < 60, grade is "F".

  2. Otherwise, if testScore < 70, grade is "D".

  3. Otherwise, if testScore < 80, grade is "C".

  4. Otherwise, if testScore < 90, grade is "B".

  5. Otherwise, grade is "A".

Nested Implementation (Grader Application)
1 private void determineGradeButton_Click(object sender, EventArgs e)
2 {
3     try
4     {
5         // Variable to hold the test score.
6         double testScore;
7 
8         // Get the test score.
9         testScore = double.Parse(testScoreTextBox.Text);
10 
11         // Determine the grade.
12         if (testScore < 60)
13         {
14             gradeLabel.Text = "F";
15         }
16         else
17         {
18             if (testScore < 70)
19             {
20                 gradeLabel.Text = "D";
21             }
22             else
23             {
24                 if (testScore < 80)
25                 {
26                     gradeLabel.Text = "C";
27                 }
28                 else
29                 {
30                     if (testScore < 90)
31                     {
32                         gradeLabel.Text = "B";
33                     }
34                     else
35                     {
36                         gradeLabel.Text = "A";
37                     }
38                 }
39             }
40         }
41     }
42     catch (Exception ex)
43     {
44         // Display an error message.
45         MessageBox.Show(ex.Message);
46     }
47 }

The if-else-if Statement

Syntax and Mechanics

The if-else-if statement is a specialized C# decision structure designed to evaluate a chain of conditions cleanly.

General Format
if (BooleanExpression_1)
{
    // Statements executed if BooleanExpression_1 is true
}
else if (BooleanExpression_2)
{
    // Statements executed if BooleanExpression_2 is true
}
else if (BooleanExpression_3)
{
    // Statements executed if BooleanExpression_3 is true
}
else
{
    // Statements executed if none of the expressions are true
}
Execution Rules
  1. Evaluates BooleanExpression_1. If true, executes its statement block and exits the entire if-else-if structure immediately.

  2. If BooleanExpression_1 is false, control jumps directly to the next else if clause and evaluates BooleanExpression_2.

  3. The process repeats sequentially down the chain until a condition evaluates to true.

  4. If no condition evaluates to true, the default statement block following the final else clause is executed.

Grader2 Implementation

The Grader2 project replaces nested if-else blocks with an if-else-if structure.

1 private void determineGradeButton_Click(object sender, EventArgs e)
2 {
3     try
4     {
5         // Variable to hold the test score.
6         double testScore;
7 
8         // Get the test score.
9         testScore = double.Parse(testScoreTextBox.Text);
10 
11         // Determine the grade.
12         if (testScore < 60)
13         {
14             gradeLabel.Text = "F";
15         }
16         else if (testScore < 70)
17         {
18             gradeLabel.Text = "D";
19         }
20         else if (testScore < 80)
21         {
22             gradeLabel.Text = "C";
23         }
24         else if (testScore < 90)
25         {
26             gradeLabel.Text = "B";
27         }
28         else
29         {
30             gradeLabel.Text = "A";
31         }
32     }
33     catch (Exception ex)
34     {
35         // Display an error message.
36         MessageBox.Show(ex.Message);
37     }
38 }
Comparison: if-else-if vs. Deeply Nested if-else

While functionally identical, deeply nested if-else structures present distinct disadvantages during code maintenance and debugging:

  1. Code Complexity: Logic quickly becomes convoluted and hard to track visually.

  2. Horizontal Drift / Scrolling: Cumulative indentation pushes code far to the right, requiring horizontal screen scrolling in Visual Studio or causing word-wrapping when printed on paper.

  3. Alignment Clarity: if-else-if aligns all if, else if, and else keywords vertically at a single indentation depth, keeping line lengths shorter.

Checkpoints & Practice Code

Checkpoint 4.11

Problem: Convert the following nested if-else decision structure into an equivalent if-else-if statement:

// Original Nested Format
if (number == 1)
{
    MessageBox.Show("One");
}
else
{
    if (number == 2)
    {
        MessageBox.Show("Two");
    }
    else
    {
        if (number == 3)
        {
            MessageBox.Show("Three");
        }
        else
        {
            MessageBox.Show("Unknown");
        }
    }
}

Solution:

// Converted if-else-if Format
if (number == 1)
{
    MessageBox.Show("One");
}
else if (number == 2)
{
    MessageBox.Show("Two");
}
else if (number == 3)
{
    MessageBox.Show("Three");
}
else
{
    MessageBox.Show("Unknown");
}