Getting Started
So far, we have seen how a computer can follow a list of instructions in sequence. However, a program's real power comes from its ability to make decisions. Just as you might decide to take an umbrella IF it is raining, a computer program can execute different instructions based on whether a certain condition is true or false. This decision-making process is a core part of nearly every useful application, from a game that checks for a high score to a navigation app that reroutes you around traffic.
What You Should Be Able to Do
Explain how conditional statements control the flow of an algorithm.
Evaluate expressions using relational and logical operators to determine a Boolean result.
Trace the execution path of an algorithm that includes
IFandIF-ELSEstatements.Write an algorithm that uses conditionals to solve a problem by choosing between different outcomes.
Key Concepts & Application
The Core Idea
An algorithm is a finite set of instructions that accomplishes a specific task. While some algorithms are simple sequential lists, most need to adapt to changing data or user input. The process of directing an algorithm's flow to one path or another is called selection. Selection allows a program to ask a question and then choose a set of actions based on the answer.
Think of it like a simple flowchart for getting ready in the morning. A key question might be: "Is it raining?" If the answer is "yes," you follow the path that includes "get an umbrella." If the answer is "no," you skip that step. In programming, these questions are called conditions, and they form the basis of all decision-making in software.
Logic & Application
Conditional statements work by evaluating a condition to a single Boolean value: either true or false. A Boolean value is a data type that can only hold one of two possible values, representing truth or falsehood. To create these conditions, we use two special types of operators.
1. Relational Operators
Relational operators are used to compare two values. The result of the comparison is always true or false.
| Operator | Meaning | Example | Result |
|---|---|---|---|
a = b | a is equal to b | 5 = 5 | true |
a ≠ b | a is not equal to b | score ≠ 100 | true (if score is 90) |
a > b | a is greater than b | 10 > 5 | true |
a < b | a is less than b | age < 18 | false (if age is 21) |
a ≥ b | a is greater than or equal to b | points ≥ 1000 | true (if points is 1000) |
a ≤ b | a is less than or equal to b | items ≤ 3 | false (if items is 5) |
2. Logical Operators
Logical operators are used to combine or modify Boolean values. They are essential for building more complex conditions.
| Operator | Meaning | Example | Result |
|---|---|---|---|
a AND b | true only if both a and b are true | (age > 18) AND (hasLicense = true) | true (if both are true) |
a OR b | true if at least one of a or b is true | (isWeekend = true) OR (isHoliday = true) | true (if it's a weekend) |
NOT a | Inverts the value of a | NOT (isRaining = true) | false |
Annotated Pseudocode Examples
Example 1: The IF Statement
An IF statement executes a block of code only if its condition is true. If the condition is false, the block is skipped entirely.
// This algorithm checks if a user has earned enough points for a bonus.
points <- 950
hasBonus <- false
IF (points > 1000)
{
// This block only runs if the condition (points > 1000) is true.
hasBonus <- true
DISPLAY("Congratulations! You earned a bonus!")
}
DISPLAY("Game Over")
In this example, since points is 950, the condition 950 > 1000 is false. The code inside the {} is skipped, and the program moves on to display "Game Over".
Example 2: The IF-ELSE Statement
An IF-ELSE statement provides two possible paths. The IF block runs if the condition is true, and the ELSE block runs if the condition is false. One of the two blocks will always execute.
// This algorithm checks if a person is old enough to vote.
age <- 20
IF (age ≥ 18)
{
// This block runs because the condition (20 ≥ 18) is true.
DISPLAY("You are eligible to vote.")
}
ELSE
{
// This block is skipped.
DISPLAY("You are not yet eligible to vote.")
}
Here, age is 20, so the condition 20 ≥ 18 is true. The program displays the first message and completely ignores the ELSE block.
Tracing & Analysis
Logic Trace
Let's trace the voting algorithm with two different inputs to see how the path of execution changes.
Scenario 1: age is initialized to 16
| Line of Code | Condition | Condition Result | Action Taken | Output |
|---|---|---|---|---|
age <- 16 | Variable age is set to 16. | |||
IF (age ≥ 18) | 16 ≥ 18 | false | The condition is false. | |
ELSE | The ELSE block is executed. | |||
DISPLAY(...) | The message is displayed. | "You are not yet eligible to vote." |
Scenario 2: age is initialized to 25
| Line of Code | Condition | Condition Result | Action Taken | Output |
|---|---|---|---|---|
age <- 25 | Variable age is set to 25. | |||
IF (age ≥ 18) | 25 ≥ 18 | true | The condition is true. | |
DISPLAY(...) | The message is displayed. | "You are eligible to vote." | ||
ELSE | The ELSE block is skipped. |
This trace demonstrates how a single algorithm can produce different results based on its input data, thanks to the power of selection.
Key Terminology & Logic
A quick reference for the building blocks of conditionals.
IF (condition): Executes the following code block only ifconditionevaluates totrue.ELSE: Paired with anIF. Executes the following code block only if theIF'sconditionevaluates tofalse.a = b: Tests ifaandbare equal.a ≠ b: Tests ifaandbare not equal.a > b: Tests ifais greater thanb.a < b: Tests ifais less thanb.a ≥ b: Tests ifais greater than or equal tob.a ≤ b: Tests ifais less than or equal tob.a AND b: Evaluates totrueif bothaandbaretrue.a OR b: Evaluates totrueif eitheraorb(or both) aretrue.NOT a: Inverts the Boolean value ofa.
Core Concepts & Terminology
Algorithm: A finite, step-by-step set of instructions designed to perform a specific task or solve a problem.
Selection: A control structure in programming that uses a condition to determine which of two or more blocks of code will be executed.
Boolean Value: A data type that can only be
trueorfalse. Conditions in selection statements always evaluate to a Boolean value.Conditionals: The programming statements that implement selection, such as
IFandIF-ELSE.Relational Operators: Symbols used to compare two values, such as
=(equal to),>(greater than), and≠(not equal to). The result of a comparison is a Boolean value.Logical Operators: Symbols (
AND,OR,NOT) used to combine or modify Boolean expressions to create more complex conditions.Core Logic:
IFStatement:IF (condition) { // Code to execute if condition is true }This structure executes a set of instructions only when a specific condition is met.
Core Logic:
IF-ELSEStatement:IF (condition) { // Code to execute if condition is true } ELSE { // Code to execute if condition is false }This structure guarantees that one of two code paths will be followed based on the condition.
Core Skill Check
Logic Tracing: What is the final value of
scoreafter this pseudocode runs?x <- 10,y <- 15,score <- 100.IF ((x > 5) AND (y < 10)) { score <- score + 25 }Debugging: Identify the logic error in this pseudocode intended to give a discount to users younger than 18 or older than 65.
IF ((age < 18) AND (age > 65)) { discount <- true }Application: Describe a real-world example of how a social media app might use an
IF-ELSEstatement to check if a post has new comments.
Common Misconceptions & Clarifications
Confusing Assignment and Comparison: In pseudocode,
<-is used for assignment (giving a variable a value), while=is used for comparison (checking for equality). Mixing these up is a common source of errors.An
ELSEMust Follow anIF: AnELSEstatement cannot exist on its own. It is always the second part of anIF-ELSEstructure, providing the alternative path when theIFcondition is false.The
IFBlock is Not Guaranteed to Run: The code inside anIFstatement's block is conditional. It will be completely skipped if the condition evaluates tofalse.ANDvs.ORLogic:ANDis strict—all parts of the condition must be true.ORis flexible—only one part needs to be true. Choosing the wrong one can lead to incorrect program behavior.
Summary
Conditionals are the fundamental tool that allows algorithms to make decisions. By using IF and IF-ELSE statements, a program can follow different paths based on specific criteria. These decisions are driven by conditions, which are expressions built with relational and logical operators that evaluate to a Boolean value of true or false. This process of selection transforms a simple, sequential program into a dynamic and responsive one, capable of handling varied inputs and complex logic. Mastering conditionals is a critical step toward creating sophisticated and intelligent software.