Uploaded by palesafitco

Selection Structures in Programming: If-Then-Else, AND, OR, NOT

advertisement
Understanding the Selection Structure in Programming
The ability of computer programs to make decisions is what often makes them appear
intelligent. For instance, a medical diagnosis program that identifies diseases based on
symptoms or a GPS application that suggests different routes based on the destination
both showcase decision-making capabilities. This is achieved through a fundamental
programming concept known as the selection structure.
The Selection Structure
The selection structure is one of the three basic control structures in programming (the
others being sequence and loop structures). It begins with the evaluation of a Boolean
expression, which results in one of two outcomes: true or false. Based on the result, the
program takes one of two possible paths.
In flowcharts, this is represented by a diamond-shaped decision symbol. From this
diamond, two branches emerge: typically, one goes to the right (Yes or True path) and the
other to the left (No or False path). These branches are mutually exclusive, meaning the
logic can proceed down only one path based on the Boolean evaluation.
The dual-alternative selection structure is often referred to as an if-then-else structure:
•
If the condition is true, then perform a specific action.
•
Else, perform a different action.
Some flowchart styles may differ (e.g., placing a branch at the bottom), but consistency
within the same diagram is key for readability.
Single-Alternative Selection (If-Then)
There are cases where an action is required only for one outcome of a condition. This is
called a single-alternative selection, or an if-then structure. Here, there is no alternative
or "else" action if the condition is false.
Example: Payroll Program
In a sample program that calculates weekly pay for employees (at a fixed rate of $15.00/hr
with no deductions), the main logic includes modules such as:
•
housekeeping()
•
detailLoop()
•
finish()
Within the detailLoop() module, a dual-alternative selection checks if an employee worked
more than 40 hours. If true, the program calculates overtime pay (1.5x the hourly rate for
hours beyond 40). Otherwise, it performs a regular pay calculation.
Pseudocode and Flowcharts
Throughout programming, both flowcharts and pseudocode are used to design solutions.
Beginners may find it easier to focus on one at a time to understand the logic before
translating it into the other.
Components of a Decision:
•
If-Then Clause: Executes actions when the condition is true.
•
Else Clause: Executes actions when the condition is false.
Relational Comparison Operators
Relational operators compare two values and return a Boolean result. Common operators
include:
1. == (equal to)
2. != (not equal to)
3. > (greater than)
4. < (less than)
5. >= (greater than or equal to)
6. <= (less than or equal to)
Common Error:
Using the wrong operator can cause logic errors. For example:
•
If your program is supposed to select employees "over 65" and you use > 65,
employees who are exactly 65 will be excluded. Clarify ambiguous terms like "over,"
"at least," "no more than," and "not under" by confirming with the program requester.
Understanding AND Logic
Sometimes, a decision must be based on multiple conditions. This is called a compound
condition. For example, a mobile service provider might charge extra if:
•
A customer makes more than 100 calls
•
Total call minutes exceed 500
Here, both conditions must be true to trigger the premium charge. This logic is
implemented using the AND operator, either through:
•
Nested if statements (if within another if)
•
Cascading if statements (multiple nested conditions)
Efficiency in Nesting Decisions
When nesting decisions, the order in which conditions are evaluated can affect
performance. Evaluate the most likely false condition first to potentially reduce
unnecessary processing.
Using the AND Operator
Most programming languages allow combining Boolean expressions using an AND
operator (e.g., && or and).
Example:
if callsMade > 100 AND callMinutes > 500
add $20 premium
Here, both conditions must be met for the action to take place.
Avoiding Common Errors in AND Selection
When combining multiple conditions:
•
Ensure all conditions are correctly nested.
•
Verify the entire second condition is placed within the first if it depends on the first
being true.
Improper nesting can lead to incorrect results or logical errors. For instance, charging a
premium when only one of the two conditions is true would be a mistake.
Understanding OR, AND, and NOT Logic in Programming
1. Understanding OR Logic
In programming, OR logic is used when you want an action to be performed if at least one
of multiple conditions is true. This is known as an OR decision. For instance, if someone
asks: "Are you free for dinner Friday or Saturday?"—you only need to be free on one of those
days for the overall answer to be yes.
Example Scenario: A mobile phone company has the following billing policy:
•
Basic monthly service: $30
•
An additional $20 is billed if a customer:
o
Makes more than 100 calls, OR
o
Sends more than 200 text messages
Using OR logic, either condition being true will trigger the extra $20 charge.
2. Writing OR Selections for Efficiency
When writing OR logic, the order of conditions can affect performance, especially when
one condition is more likely to be true than the other.
Example: Out of 1000 customers:
•
900 make more than 100 calls
•
500 send more than 200 text messages
In this case, it’s more efficient to check calls first, as the program can potentially avoid
evaluating the second condition more often.
3. Using the OR Operator
Instead of using two nested if statements, most programming languages allow combining
conditions with an OR operator.
Syntax Example:
if (callsMade > CALLS OR textsSent > TEXTS) then
customerBill = customerBill + PREMIUM
endif
Truth Table for OR:
Condition A Condition B A OR B
False
False
False
False
True
True
True
False
True
True
True
True
4. Avoiding Common Errors in OR Selections
a. Boolean Expressions Must Be Complete: Each condition in an OR expression must be
a full comparison.
Incorrect:
callsMade = 0 OR > 2000
Correct:
(callsMade = 0) OR (callsMade > 2000)
b. Use Parentheses for Clarity:
if (callsMade = 0) OR (callsMade > 2000) then
output "Irregular usage"
endif
c. Avoid Code Duplication: Don’t repeat the same action within both branches—structure
logic cleanly.
5. Understanding NOT Logic
The NOT operator is used to reverse the result of a Boolean expression. It is a unary
operator, meaning it only needs one operand.
Example:
if NOT (age < 18) then
output "Can register to vote"
endif
Truth Table for NOT:
Note: Parentheses clarify which part of the expression NOT applies to. Without them, the
logic might be misinterpreted.
Avoid Confusing Logic: Negative expressions are harder to understand. Prefer positive
statements when possible.
Confusing:
if NOT (age < 18) then
Clearer:
if age >= 18 then
Common Error Example: Incorrect:
if NOT (employeeDept = 1) OR NOT (employeeDept = 2) then
output "Employee is not in Department 1 or 2"
endif
This incorrectly prints the message for Department 2 employees.
Correct:
if NOT (employeeDept = 1 OR employeeDept = 2) then
output "Employee is not in Department 1 or 2"
endif
6. Understanding Precedence When Combining AND and OR Operators
AND and OR can be combined in one expression. However, AND has higher precedence
and will be evaluated first.
Example: All tests must be passed:
if (score1 >= MIN_SCORE) AND (score2 >= MIN_SCORE) AND (score3 >= MIN_SCORE) then
classGrade = "Pass"
else
classGrade = "Fail"
endif
Example: Only one test must be passed:
if (score1 >= MIN_SCORE) OR (score2 >= MIN_SCORE) OR (score3 >= MIN_SCORE) then
classGrade = "Pass"
else
classGrade = "Fail"
endif
When combining AND and OR in the same statement, always use parentheses to clarify
logic and avoid unintended precedence.
Conclusion
Understanding how to use OR, AND, and NOT logic in programming is essential for writing
accurate and efficient decision-making structures. Always ensure clarity with complete
conditions and parentheses, and consider efficiency and readability in your logic design.
Download