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 hours. If true, the employee receives extra pay for all hours over ; 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
trueorfalse.
Execution Logic
When the
ifstatement executes, the Boolean expression is tested.If the expression evaluates to
true, the statements inside the curly braces are executed.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 s 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 |
|---|---|
| Is |
| Is |
| Is |
| Is |
| Is |
| Is |
Comparative Examples
length > width: Determines whetherlengthis greater thanwidth. Evaluates totrueiflengthis strictly larger, otherwisefalse.length < width: Determines whetherlengthis less thanwidth.
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 >= 4a >= 28 >= aa <= 4a <= 94 <= 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 == 4istrue.a == 2isfalse.
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, andc = 4:a != bevaluates totrue(since ).b != cevaluates totrue(since ).a != cevaluates tofalse(since ).
Implementation Examples and Formatting
Single Conditional Action Example
if (sales > 50000)
{
bonus = 500;
}
If sales exceeds , bonus is assigned the value . 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:
bonusis set to .commissionRateis set toA 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 , it displays a congratulatory message box.
Project Source Location:
Test Score Averageproject in theChap04folder 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
tryblock (lines 24–43) and acatchblock (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:
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 viaMessageBox.Show("Congratulations! Great job!");.Line 45–48 (catch block): Catches exceptions (
Exception ex) and displays the default message usingMessageBox.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 (
"") totest1TextBox.Text,test2TextBox.Text, andtest3TextBox.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
Save project and press F5 (or click Start Debugging).
Test Run 1: Enter scores , , and . Click Calculate Average. The output displays formatted average. Click Clear.
Test Run 2: Enter scores , , and . Click Calculate Average. Output displays average and triggers the congratulatory dialog box.
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;
}