Chapter 4 Lectures: 4.1 Decision Structures and the if Statement

Control Structures and Decision Logic

A control structure is a logical design that controls the order in which a set of statements execute.

Sequence Structure

A sequence structure is a set of statements that execute in the order that they appear, from top to bottom.

int ageInYears, ageInDays;
ageInYears = int.Parse(ageTextBox.Text);
ageInDays = ageInYears * 365;
daysLabel = ageInDays.ToString();

Although heavily utilized in programming, the sequence structure cannot handle every type of task. Certain problems cannot be solved by performing a set of ordered steps sequentially. For example, a pay-calculating program determining whether an employee has worked overtime must evaluate if the employee worked more than 4040 hours. If true, the employee receives extra pay for all hours over 4040; otherwise, the overtime calculation is skipped.

Decision Structures (Selection Structures)

Programs with conditional logic require a decision structure (also known as a selection structure). A decision structure allows a program to perform actions only under specific circumstances.

In its simplest form, a decision structure performs a specific action only if a certain condition exists. If the condition does not exist, the action is skipped.

  • Flowchart Mechanics:

    • Diamond Symbol: Represents a true-false condition that must be tested.

    • True Path: Leads to an action being performed.

    • False Path: Leads to skipping the action.

    • Conditionally Executed Action: An action performed strictly when a certain condition evaluates to true (e.g., testing the condition "Cold outside"; if true, the action "Wear a coat" is executed; if false, it is skipped).

Single-Alternative Decision Structures

A single-alternative decision structure provides only one alternative path of execution. If the condition in the diamond symbol is true, the alternative path is taken. Otherwise, the structure is exited.

The C# if Statement

In C#, a single-alternative decision structure is written using the if statement.

Syntax Format
if (expression)
{
    statement;
    statement;
    etc.
}
  • The statement begins with the keyword if, followed by an expression enclosed in parentheses.

  • Statements inside curly braces {} begin on subsequent lines.

  • Boolean Expression: An expression enclosed inside the parentheses that evaluates to either true or false.

Execution Logic
  1. When the if statement executes, the Boolean expression is tested.

  2. If the expression evaluates to true, the statements inside the curly braces are executed.

  3. If the expression evaluates to false, the statements inside the curly braces are skipped.

Single-Statement Syntax Exception

If an if statement controls only one conditionally executed statement, the curly braces are not strictly required:

if (expression)
    Statement;

When executed, if the Boolean expression is true, the single statement on the next line executes; if false, it is skipped.

Programming Best Practice: Always enclose conditionally executed statements in curly braces {} regardless of statement count. This coding style minimizes syntax errors and prevents accidentally omitting braces when adding additional statements later.

Boolean Expressions and Relational Operators

Boolean expressions are named in honor of the 18001800s English mathematician George Boole, who invented a mathematical system using abstract concepts of true and false for computations.

A Boolean expression tested by an if statement is typically formed using a relational operator. A relational operator determines whether a specific relationship exists between two values.

C# Relational Operators

Operator

Meaning

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

==

Equal to

!=

Not equal to

Relational Expressions Overview

Expression

Meaning

x > y

Is x greater than y?

x < y

Is x less than y?

x >= y

Is x greater than or equal to y?

x <= y

Is x less than or equal to y?

x == y

Is x equal to y?

x != y

Is x not equal to y?

Comparative Examples
  • length > width: Determines whether length is greater than width. Evaluates to true if length is strictly larger, otherwise false.

  • length < width: Determines whether length is less than width.

Detailed Analysis of Relational Operators

The >= and <= Operators

These operators test for multiple relationships simultaneously:

  • >= (Greater than or equal to): Tests if the left operand is greater than or equal to the right operand.

  • <= (Less than or equal to): Tests if the left operand is less than or equal to the right operand.

Assuming variable a = 4, the following expressions all evaluate to true:

  • a >= 4

  • a >= 2

  • 8 >= a

  • a <= 4

  • a <= 9

  • 4 <= a

The == Operator

Determines whether the left operand is equal to the right operand.

  • If operands contain identical values, the expression evaluates to true.

  • Assuming a = 4:

    • a == 4 is true.

    • a == 2 is false.

  • Critical Distinction: The equality operator consists of two consecutive equal signs (==). Do not confuse it with the assignment operator (=), which consists of a single equal sign.

The != Operator

The not-equal-to operator (!=) determines whether the left operand is not equal to the right operand, serving as the logical opposite of ==.

  • Assuming a = 4, b = 6, and c = 4:

    • a != b evaluates to true (since 4≠64 \neq 6).

    • b != c evaluates to true (since 6≠46 \neq 4).

    • a != c evaluates to false (since 4=44 = 4).

Implementation Examples and Formatting

Single Conditional Action Example
if (sales > 50000)
{
    bonus = 500;
}

If sales exceeds 5000050000, bonus is assigned the value 500500. Otherwise, the assignment statement is skipped.

Multiple Conditional Actions Example
if (sales > 50000)
{
    bonus = 500;
    commissionRate = 0.12;
    MessageBox.Show("You met your sales quota!");
}

If sales > 50000 is true, all three statements inside the block execute sequentially:

  1. bonus is set to 500500.

  2. commissionRate is set to 0.120.12

  3. A message box displays "You met your sales quota!".

Code Formatting in Visual Studio

Visual Studio automatically indents conditionally executed statements inside an if structure. While indentation is not syntactically required by the C# compiler, it visually sets conditional blocks apart from surrounding code, allowing programmers to easily determine control flows at a glance and improving readability and debugging.

Tutorial 4-1: Test Score Average Application Implementation

Application Overview

The Test Score Average application calculates the average of three user-entered test scores. If the calculated average exceeds 95.095.0, it displays a congratulatory message box.

  • Project Source Location: Test Score Average project in the Chap04 folder of Student Sample Programs (www.pearsonhighered.com/gaddis).

Step-by-Step Implementation Procedure
Step 1: Open Project

Start Visual Studio. Open the Test Score Average project located in the Chap04 folder.

Step 2: Form Designer Overview

Open Form1 in the Designer view to inspect controls (test1TextBox, test2TextBox, test3TextBox, averageLabel, calculateButton, clearButton, exitButton).

Step 3: Implement calculateButton_Click Event Handler

Double-click calculateButton to create the calculateButton_Click handler. Add the following logic (Lines 22–49 of Program 4-1):

  • Line 22 (try-catch statement): Encloses the code inside a try block (lines 24–43) and a catch block (lines 47–48) to gracefully handle invalid inputs (such as non-numeric text) without crashing the application.

  • Line 24: Declares constant const double HIGH_SCORE = 95.0;.

  • Line 25: Declares variables double test1, test2, test3, average;.

  • Lines 28–30: Parses inputs:

    • test1 = double.Parse(test1TextBox.Text);

    • test2 = double.Parse(test2TextBox.Text);

    • test3 = double.Parse(test3TextBox.Text);

  • Line 33: Calculates average:

average=test1+test2+test33.0\text{average} = \frac{\text{test1} + \text{test2} + \text{test3}}{3.0}

  • Line 36: Formats and displays output: averageLabel.Text = average.ToString("n1");.

  • Line 40–43 (if statement): Checks if average > HIGH_SCORE. If true, displays message box via MessageBox.Show("Congratulations! Great job!");.

  • Line 45–48 (catch block): Catches exceptions (Exception ex) and displays the default message using MessageBox.Show(ex.Message);.

Step 4: Implement clearButton_Click Event Handler

Double-click clearButton in Designer and enter code (Lines 54–61):

  • Lines 55–57: Clears input text boxes by assigning empty strings ("") to test1TextBox.Text, test2TextBox.Text, and test3TextBox.Text.

  • Line 58: Clears average display label (averageLabel.Text = "";).

  • Line 61: Restores focus to test1TextBox (test1TextBox.Focus();).

Step 5: Implement exitButton_Click Event Handler

Double-click exitButton in Designer and enter code (Lines 66–67):

  • Line 67: Closes the application form (this.Close();).

Step 6: Test Execution
  1. Save project and press F5 (or click Start Debugging).

  2. Test Run 1: Enter scores 8080, 9090, and 7575. Click Calculate Average. The output displays formatted average. Click Clear.

  3. Test Run 2: Enter scores 100100, 9797, and 9999. Click Calculate Average. Output displays average and triggers the congratulatory dialog box.

  4. Click Exit to close the form.

Program 4-1 Complete Source Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test_Score_Average
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void calculateButton_Click(object sender, EventArgs e)
        {
            try
            {
                const double HIGH_SCORE = 95.0;  // High Score value
                double test1, test2, test3, average; // Variables

                // Get the test scores from the TextBoxes.
                test1 = double.Parse(test1TextBox.Text);
                test2 = double.Parse(test2TextBox.Text);
                test3 = double.Parse(test3TextBox.Text);

                // Calculate the average test score.
                average = (test1 + test2 + test3) / 3.0;

                // Display the average, rounded to 2 decimal places.
                averageLabel.Text = average.ToString("n1");

                // If the average is a high score, congratulate
                // the user with a message box.
                if (average > HIGH_SCORE)
                {
                    MessageBox.Show("Congratulations! Great job!");
                }
            }
            catch (Exception ex)
            {
                // Display the default error message.
                MessageBox.Show(ex.Message);
            }
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            // Clear the TextBoxes and the averageLabel control.
            test1TextBox.Text = "";
            test2TextBox.Text = "";
            test3TextBox.Text = "";
            averageLabel.Text = "";

            // Reset the focus to test1.
            test1TextBox.Focus();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            // Close the form.
            this.Close();
        }
    }
}

Checkpoint Review and Self-Assessment

4.1 What is a control structure?

A control structure is a logical design that controls the order in which a set of statements execute within a program.

4.2 What is a decision structure?

A decision structure (or selection structure) is a control structure that executes a set of statements only under certain circumstances or conditions.

4.3 What is a single-alternative decision structure?

A single-alternative decision structure is a decision structure that provides only one alternative path of execution. If the condition being tested is true, the program takes the alternative path; if false, the action is skipped and execution continues outside the structure.

4.4 What is a Boolean expression?

A Boolean expression is an expression that evaluates to either true or false.

4.5 What types of relationships between numeric values can you test with relational operators?

Relational operators allow testing whether one numeric value is:

  • Greater than (>)

  • Less than (<)

  • Greater than or equal to (>=)

  • Less than or equal to (<=)

  • Equal to (==)

  • Not equal to (!=)

4.6 Write an if statement that determines whether the variable y is equal to 20. If it is, assign 0 to the variable x.
if (y == 20)
{
    x = 0;
}
4.7 Write an if statement that determines whether the variable sales is greater than or equal to 10,000. If it is, assign 0.2 to the variable commissionRate.
if (sales >= 10000)
{
    commissionRate = 0.2;
}