Conditional Branching: If-Then and If-Then-Else

Master the art of decision-making in programming - a essential CSEC IT skill!

1

Introduction: Making Decisions in Programming

What is Conditional Branching?

Conditional branching is a fundamental concept in programming that allows your program to make decisions based on certain conditions. Just like we make decisions every day—checking if it's raining before going outside, or deciding what to eat based on what's available—programs use conditional statements to choose which code to execute.

In computer science, conditional branching is sometimes called decision-making or selection structures. These structures allow your program to follow different paths depending on whether specific conditions are true or false.

How Decisions Work in Algorithms

When we create algorithms, we often need to make choices. An algorithm is a step-by-step solution to a problem, and sometimes the next step depends on the current situation. This is where conditional branching comes in. The program evaluates a condition (a statement that can be either true or false) and then decides which set of instructions to execute based on that evaluation.

Real-Life Decision Examples

We make conditional decisions constantly without even realizing it. Here are some everyday examples that show how conditional thinking works:

Real-Life Situation The Condition Action if True Action if False
Checking if you passed an exam Marks ≥ 50 Celebrate your success! Start studying for the resit
Deciding what to wear Temperature > 30°C Wear light clothing Wear warm clothes
Buying a drink at lunch Money > $5.00 Purchase the drink Save your money
Checking age for a movie Age ≥ 18 Watch the adult movie Choose a family movie
Caribbean Context: In Jamaica, Trinidad, or any Caribbean island, you might check if the price of dasheen at the market is less than $50 per pound before buying. Or you might decide whether to go to the beach based on whether it's the dry season or rainy season. These everyday decisions are exactly how conditional branching works in programming!

Why Do We Need Conditional Branching?

Without conditional branching, programs would be very limited. They would simply execute the same instructions in the same order every time, no matter what data they receive or what situations arise. Conditional branching makes programs smart and flexible because they can:

  • Respond differently to different inputs
  • Validate user input (check if it's correct)
  • Handle error conditions gracefully
  • Make calculations based on specific criteria
  • Create interactive and dynamic user experiences
2

Conditions and Logical Tests

What is a Condition?

A condition (also called a Boolean expression) is a statement that can be evaluated as either TRUE or FALSE. Conditions are the foundation of all conditional branching. They compare values and determine whether a relationship exists between them.

Relational Operators

Relational operators compare two values and return TRUE or FALSE based on their relationship. These operators are essential for creating conditions that drive decision-making in your programs.

Operator Meaning Example Result (if x=10, y=5)
= Equal to x = y FALSE (10 ≠ 5)
Not equal to x ≠ y TRUE (10 ≠ 5)
< Less than x < y FALSE (10 is not less than 5)
> Greater than x > y TRUE (10 is greater than 5)
Less than or equal to y ≤ x TRUE (5 ≤ 10)
Greater than or equal to x ≥ y TRUE (10 ≥ 5)
Common Mistake: Assignment vs. Comparison

A very common error among beginners is confusing the assignment operator (=) with the comparison operator (=). In pseudocode and many programming languages:

  • x = 5 means "assign the value 5 to variable x" (this is not a condition)
  • x = 5 (in a condition) means "check if x equals 5" (this evaluates to TRUE or FALSE)

Some pseudocode conventions use == for comparison to avoid confusion, but CSEC uses = for both (context determines the meaning).

Logical Operators

Logical operators combine multiple conditions to create more complex decision logic. The three main logical operators are AND, OR, and NOT. These allow you to check multiple conditions at once.

AND Operator

The AND operator returns TRUE only if BOTH conditions are TRUE. If either condition is FALSE, the result is FALSE.

OR Operator

The OR operator returns TRUE if AT LEAST ONE of the conditions is TRUE. It only returns FALSE if BOTH conditions are FALSE.

Truth Tables

A truth table shows all possible combinations of TRUE and FALSE values and what the result would be for each combination. Understanding truth tables is essential for mastering logical operations.

AND Truth Table

Condition A Condition B A AND B
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE

OR Truth Table

Condition A Condition B A OR B
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

NOT Truth Table

Condition A NOT A
TRUE FALSE
FALSE TRUE

Example: Using Logical Operators

Consider a school that offers a scholarship to students who have:

  • An average of 85% or higher AND perfect attendance, OR
  • An average of 90% or higher (attendance doesn't matter)

Using pseudocode:

IF (Average >= 85 AND Attendance = "Perfect") OR Average >= 90 THEN
    Award scholarship
ENDIF
Remember: In the Caribbean CSEC examinations, you may see logical operators written in different ways. Some conventions use:
  • && or AND for AND
  • || or OR for OR
  • ! or NOT for NOT
Always use the convention specified in your syllabus materials, which for CSEC is typically the word form (AND, OR, NOT).
3

The IF-THEN Structure

What is the IF-THEN Statement?

The IF-THEN structure is the simplest form of conditional branching. It executes a block of code only if a specific condition is TRUE. If the condition is FALSE, the program simply skips the code block and continues with the next statement.

Think of it like this: "IF it's raining, THEN take an umbrella." If it's not raining, you don't take an umbrella and just go about your day.

When to Use IF-THEN

Use the IF-THEN structure when you want to:

  • Perform an action only under certain conditions
  • Skip code when the condition isn't met
  • Validate input or check for errors
  • Apply filters or conditions without needing an alternative action

IF-THEN Syntax

IF condition THEN
    statement(s) to execute if condition is TRUE
ENDIF
Important: Don't Forget ENDIF!

In CSEC pseudocode, ENDIF is required to mark the end of the IF-THEN block. Forgetting ENDIF is one of the most common mistakes students make! The program needs to know where the conditional code ends.

Example 1: Simple Grade Check

A teacher wants to display a message only if a student's score is above 75 (distinction level).

// Input the student's score
INPUT Score

// Check if score is 75 or above
IF Score >= 75 THEN
    OUTPUT "Distinction! Great work!"
ENDIF

OUTPUT "Processing complete."

What happens:

  • If Score = 82: The message "Distinction! Great work!" displays, followed by "Processing complete."
  • If Score = 60: Only "Processing complete." displays (the IF block is skipped)

Example 2: Temperature Warning System

A weather station monitors temperature and issues a heat alert only when it gets too hot.

// Input the current temperature
INPUT Temperature

// Issue warning if temperature exceeds safe limit
IF Temperature > 35 THEN
    OUTPUT "HEAT ALERT: Stay hydrated and indoors!"
ENDIF

OUTPUT "Temperature reading recorded."

Example 3: Validating User Input

A program checks if a user's password meets minimum length requirements.

// Input password from user
INPUT Password

// Check if password is too short
IF LENGTH(Password) < 8 THEN
    OUTPUT "Warning: Password is too short!"
ENDIF
4

The IF-THEN-ELSE Structure

What is the IF-THEN-ELSE Statement?

The IF-THEN-ELSE structure extends the IF-THEN statement by providing an alternative action when the condition is FALSE. It creates a fork in the program: one path for when the condition is TRUE, and another path for when it's FALSE.

Think of it like this: "IF it's raining, THEN take an umbrella, ELSE wear sunglasses." You always do one or the other—there's always a backup plan.

How IF-THEN-ELSE Differs from IF-THEN

Feature IF-THEN IF-THEN-ELSE
Action when condition is TRUE Executes the code block Executes the THEN code block
Action when condition is FALSE Skips the code block Executes the ELSE code block
Code always executes No - may skip entirely Yes - one path is always taken
Use when You only need to act sometimes You need two different actions

IF-THEN-ELSE Syntax

IF condition THEN
    statement(s) to execute if condition is TRUE
ELSE
    statement(s) to execute if condition is FALSE
ENDIF

Example 1: Pass/Fail Determination

A program determines if a student passed or failed based on their exam score.

// Input the student's score
INPUT Score

// Determine pass or fail
IF Score >= 50 THEN
    OUTPUT "Congratulations! You passed!"
ELSE
    OUTPUT "Sorry, you did not pass. Better luck next time!"
ENDIF

Example 2: Discount Calculator

A store offers a 10% discount to customers who spend $100 or more.

// Input the purchase amount
INPUT Amount

// Apply discount if qualifying amount
IF Amount >= 100 THEN
    Discount = Amount * 0.10
    OUTPUT "Discount applied: $", Discount
ELSE
    OUTPUT "No discount applied. Spend $100 for 10% off!"
ENDIF

Example 3: Age Restriction Check

A cinema program checks if a moviegoer is old enough to watch a particular film.

// Input the moviegoer's age
INPUT Age

// Check age requirement
IF Age >= 18 THEN
    OUTPUT "You may watch this movie. Enjoy!"
ELSE
    OUTPUT "Sorry, you are not old enough for this movie."
ENDIF
Real Caribbean Example: Imagine a shop in Port of Spain, Trinidad, that sells rum. The shop might use an IF-THEN-ELSE structure to check if a customer is 18 years or older before allowing a purchase. If they're under 18, the shop outputs a friendly message about returning when they're older. This is exactly the type of real-world application you'll see in Caribbean business scenarios!
5

Flowchart Representation of Conditional Branching

The Decision (Diamond) Symbol

In flowcharts, a decision or diamond symbol represents a condition that can be TRUE or FALSE. The flowchart branches into different paths based on the result of the decision. This visual representation helps you understand the flow of control in your program.

Reading Flowchart Paths

Flowcharts use labels to show which path to follow:

  • YES/TRUE - Take this path if the condition is true
  • NO/FALSE - Take this path if the condition is false

Flowchart Example 1: IF-THEN Structure

START INPUT Score Score >= 75? YES OUTPUT "Distinction!" NO END

Flowchart Example 2: IF-THEN-ELSE Structure

START INPUT Score Score >= 50? YES OUTPUT "Pass" NO OUTPUT "Fail" END
Exam Focus: Flowcharts in CSEC

In CSEC examinations, you may be asked to:

  • Draw a flowchart from given pseudocode
  • Write pseudocode from a flowchart
  • Trace through a flowchart and determine the output
  • Identify errors in a flowchart

Always remember: The decision diamond has two exit paths (YES/NO or TRUE/FALSE), while all other symbols have only one exit path.

6

Nested IF Statements

What are Nested IF Statements?

A nested IF statement is an IF statement that is placed inside another IF or ELSE block. When you have multiple conditions to check in sequence, nesting allows you to create more complex decision-making logic.

When Are Nested IFs Necessary?

Use nested IF statements when:

  • You need to check multiple conditions in sequence
  • The second condition only matters if the first condition is true (or false)
  • You have more than two possible outcomes
  • Each decision depends on the result of a previous decision

Nested IF Syntax

IF condition1 THEN
    // First condition is TRUE
    IF condition2 THEN
        statement(s) for both conditions TRUE
    ELSE
        statement(s) for condition1 TRUE but condition2 FALSE
    ENDIF
ELSE
    // First condition is FALSE
    statement(s) for condition1 FALSE
ENDIF
Indentation Matters!

While indentation is not always required by the syntax rules, it is extremely important for readability and to avoid confusion. Properly indented code helps you (and the examiner) understand which ENDIF belongs to which IF. In CSEC, you may lose marks for poorly formatted nested IFs!

Example: Grading System with Multiple Levels

A school has the following grading system:

  • 90-100: Grade A
  • 80-89: Grade B
  • 70-79: Grade C
  • Below 70: Grade F

This requires nested IFs because we must check from highest to lowest.

// Input the student's score
INPUT Score

// Determine grade using nested IF
IF Score >= 90 THEN
    OUTPUT "Grade: A"
ELSE
    IF Score >= 80 THEN
        OUTPUT "Grade: B"
    ELSE
        IF Score >= 70 THEN
            OUTPUT "Grade: C"
        ELSE
            OUTPUT "Grade: F"
        ENDIF
    ENDIF
ENDIF

Why check from highest to lowest?

If Score = 85 and we checked for 70 first, the program would give Grade C instead of Grade B. By checking from highest to lowest, we ensure that each grade is mutually exclusive.

Example: School Admission System

A school admits students based on age and previous grades.

// Input student information
INPUT Age
INPUT PreviousGrade

// Check admission eligibility
IF Age >= 5 THEN
    // Age requirement met, now check grades
    IF PreviousGrade >= 75 THEN
        OUTPUT "Admitted with scholarship!"
    ELSE
        IF PreviousGrade >= 60 THEN
            OUTPUT "Admitted!"
        ELSE
            OUTPUT "Not admitted. Grade too low."
        ENDIF
    ENDIF
ELSE
    OUTPUT "Not admitted. Too young for school."
ENDIF
Tip: CASE or SWITCH Alternative

Some programming languages offer a CASE or SWITCH statement that can handle multiple conditions more cleanly than deeply nested IFs. However, CSEC primarily tests IF-THEN and IF-THEN-ELSE structures, so focus on mastering those first. Nested IFs are a key skill for CSEC success!

7

Conditional Branching in Algorithms

Conditional statements become truly powerful when combined with other programming constructs like input operations, assignment statements, and arithmetic operations. Let's see how these elements work together in complete algorithms.

Combining Key Programming Constructs

Construct Purpose Example
INPUT Get data from user INPUT Mark
OUTPUT Display results OUTPUT "Pass"
Assignment (=) Store values in variables Discount = Price * 0.1
Arithmetic (+, -, *, /) Perform calculations Total = Price + Tax
IF-THEN/ELSE Make decisions IF Mark >= 50 THEN...

Example 1: Bank Account Balance Check

A banking system that checks if an account has sufficient funds for a withdrawal.

// Algorithm to check account balance and process withdrawal

// Step 1: Input the current balance and withdrawal amount
INPUT Balance
INPUT WithdrawalAmount

// Step 2: Check if sufficient funds exist
IF WithdrawalAmount <= Balance THEN
    // Step 3a: Calculate new balance (arithmetic operation)
    NewBalance = Balance - WithdrawalAmount
    
    // Step 4a: Display success message with new balance
    OUTPUT "Withdrawal successful!"
    OUTPUT "New balance: $", NewBalance
ELSE
    // Step 3b: Calculate shortfall amount
    Shortfall = WithdrawalAmount - Balance
    
    // Step 4b: Display error message
    OUTPUT "Insufficient funds!"
    OUTPUT "Shortfall: $", Shortfall
ENDIF

Example 2: Bus Fare Calculator

A program that calculates bus fare based on age (children and seniors get discounts).

// Algorithm to calculate bus fare with age discounts

// Step 1: Input passenger age and base fare
INPUT Age
INPUT BaseFare

// Step 2: Determine fare based on age
IF Age < 12 THEN
    // Child fare (50% discount)
    Fare = BaseFare * 0.5
    OUTPUT "Child fare applied (50% off)"
ELSE
    IF Age >= 65 THEN
        // Senior fare (30% discount)
        Fare = BaseFare * 0.7
        OUTPUT "Senior fare applied (30% off)"
    ELSE
        // Regular fare (no discount)
        Fare = BaseFare
        OUTPUT "Regular fare"
    ENDIF
ENDIF

// Step 3: Output final fare
OUTPUT "Your fare: $", Fare

Example 3: Agricultural Yield Calculator

A farmer uses this program to calculate expected yield and determine if irrigation is needed.

// Algorithm for agricultural yield assessment

// Step 1: Input crop data
INPUT PlantedArea // in acres
INPUT ExpectedYieldPerAcre // in pounds
INPUT RainfallLastWeek // in inches

// Step 2: Calculate total expected yield
TotalExpectedYield = PlantedArea * ExpectedYieldPerAcre

// Step 3: Check if irrigation is needed
IF RainfallLastWeek < 1.5 THEN
    OUTPUT "IRRIGATION NEEDED!"
    OUTPUT "Rainfall below minimum requirement."
ELSE
    OUTPUT "Irrigation not needed this week."
ENDIF

// Step 4: Output yield information
OUTPUT "Total expected yield: ", TotalExpectedYield, " pounds"

// Step 5: Determine if yield meets target
TargetYield = 5000  // Set a target
IF TotalExpectedYield >= TargetYield THEN
    OUTPUT "Target met! Good harvest expected."
ELSE
    OUTPUT "Target not met. Consider additional care."
ENDIF
8

Interactive Learning Section

Test Your Understanding!

Try these interactive activities to check your understanding of conditional branching. Click the button to reveal the answers!

🔮 What Will Happen? Question 1

Given the following pseudocode, what will be output if the input value is 25?

INPUT Number
IF Number > 20 THEN
    OUTPUT "Big number!"
ENDIF
OUTPUT "Done"

Answer:

Both messages will be output:

Big number!

Done

Since 25 is greater than 20, the IF condition is TRUE, so "Big number!" is displayed. The program then continues and displays "Done".

🔮 What Will Happen? Question 2

What will be output if the input value is 15?

INPUT Number
IF Number > 20 THEN
    OUTPUT "Big number!"
ELSE
    OUTPUT "Small number"
ENDIF

Answer:

Small number

Since 15 is NOT greater than 20, the IF condition is FALSE, so the ELSE branch executes and "Small number" is displayed.

🔮 What Will Happen? Question 3

A student writes the following code. What is the output when Age = 18?

INPUT Age
IF Age >= 18 THEN
    OUTPUT "Adult"
ENDIF
IF Age >= 13 THEN
    OUTPUT "Teenager"
ENDIF

Answer:

Adult

Teenager

Both IF statements are evaluated independently. Since 18 is >= 18 AND 18 is >= 13, both messages appear. This demonstrates that separate IF statements don't affect each other.

🔍 Identify the Error

Find the error in this pseudocode:

INPUT Score
IF Score >= 50 THEN
    OUTPUT "Pass"
ELSE
    OUTPUT "Fail"

Error Found!

Missing ENDIF statement! The code is incomplete without the ENDIF to mark the end of the IF-THEN-ELSE structure.

Correct version:

INPUT Score
IF Score >= 50 THEN
    OUTPUT "Pass"
ELSE
    OUTPUT "Fail"
ENDIF

🔍 Identify the Error

Find the error in this pseudocode:

INPUT x
INPUT y
IF x = y THEN
    OUTPUT "Numbers are equal"
ENDIF

Potential Issue!

This code is actually correct for pseudocode! In many programming languages, you would need == for comparison, but CSEC pseudocode uses = for both assignment and comparison (context determines the meaning).

However, in actual programming languages like JavaScript, Java, or C++, this would be wrong because = means assignment, not comparison!

🎯 Scenario Problem

Write pseudocode for a program that:

  • Asks for a student's score (0-100)
  • Displays "Excellent" for scores 90 and above
  • Displays "Good" for scores 75-89
  • Displays "Satisfactory" for scores 60-74
  • Displays "Needs Improvement" for scores below 60

One Possible Solution:

INPUT Score

IF Score >= 90 THEN
    OUTPUT "Excellent"
ELSE
    IF Score >= 75 THEN
        OUTPUT "Good"
    ELSE
        IF Score >= 60 THEN
            OUTPUT "Satisfactory"
        ELSE
            OUTPUT "Needs Improvement"
        ENDIF
    ENDIF
ENDIF

Note: The conditions must be checked from highest to lowest to ensure correct categorization!

🎯 Scenario Problem

A Caribbean fruit stand sells mangoes at the following prices:

  • First 10 mangoes: $5 each
  • Additional mangoes: $3 each

Write pseudocode to calculate and display the total cost based on the number of mangoes purchased.

Solution:

INPUT NumberOfMangoes

IF NumberOfMangoes <= 10 THEN
    TotalCost = NumberOfMangoes * 5
ELSE
    First10Cost = 10 * 5
    AdditionalMangoes = NumberOfMangoes - 10
    AdditionalCost = AdditionalMangoes * 3
    TotalCost = First10Cost + AdditionalCost
ENDIF

OUTPUT "Total cost: $", TotalCost
9

Common Student Mistakes

Understanding common errors will help you avoid losing marks on your CSEC exams. Here are the mistakes that examiners see most frequently:

Mistake 1: Forgetting ENDIF

This is the most common error! Every IF statement must be closed with an ENDIF.

Wrong:

IF Score >= 50 THEN
    OUTPUT "Pass"
OUTPUT "Done"  // Missing ENDIF!

Correct:

IF Score >= 50 THEN
    OUTPUT "Pass"
ENDIF
OUTPUT "Done"
Mistake 2: Using Assignment (=) Instead of Comparison

Remember that in conditions, you need to compare values, not assign them.

Wrong:

// This assigns 50 to Score, doesn't check it!
IF Score = 50 THEN  // In some languages, this is WRONG!

Correct (in pseudocode):

// This checks if Score equals 50
IF Score = 50 THEN  // Context makes this a comparison

Note: In real programming languages, use == for comparison and = for assignment.

Mistake 3: Incorrect Logical Operators

Make sure you understand AND vs OR—they behave very differently!

Example: Checking if a number is between 10 and 20

Wrong (uses OR):

// This will be TRUE for almost any number!
IF Number >= 10 OR Number <= 20 THEN

Correct (uses AND):

// This correctly checks for the range
IF Number >= 10 AND Number <= 20 THEN
Mistake 4: Misplacing ELSE Statements

ELSE must always belong to the correct IF. In nested structures, indentation helps clarify this.

Wrong (confusing structure):

IF x > 10 THEN
    IF y > 5 THEN
        OUTPUT "A"
    ENDIF
ELSE  // Which IF does this belong to?
    OUTPUT "B"
ENDIF

Correct (clear structure):

IF x > 10 THEN
    IF y > 5 THEN
        OUTPUT "A"
    ENDIF
ELSE
    OUTPUT "B"
ENDIF

In this case, ELSE belongs to the first IF (x > 10). The inner IF (y > 5) doesn't have an ELSE.

Mistake 5: Wrong Order in Nested IFs

When checking ranges, always check from highest to lowest value!

Wrong (checks from low to high):

IF Score >= 50 THEN
    OUTPUT "Pass"
ELSE
    IF Score >= 75 THEN  // Will NEVER execute!
        OUTPUT "Good"
    ENDIF
ENDIF

Correct (checks from high to low):

IF Score >= 75 THEN
    OUTPUT "Good"
ELSE
    IF Score >= 50 THEN
        OUTPUT "Pass"
    ENDIF
ENDIF
10

CSEC Exam Focus

How Conditional Branching Appears in CSEC Exams

Conditional branching is a staple topic in the CSEC Information Technology examination. Here's how it typically appears:

1. Multiple-Choice Questions (Paper 1)

You will encounter questions testing your understanding of:

  • Identifying correct pseudocode syntax
  • Understanding the result of conditional statements
  • Selecting appropriate conditions for given scenarios
  • Logical operators and their outcomes

Example: "Which of the following pseudocode segments will output 'Adult' when Age = 17?"

2. Trace Tables (Paper 2)

Trace tables require you to step through pseudocode line by line, tracking variable values. For conditional branching, you must:

  • Evaluate each condition correctly (TRUE or FALSE)
  • Follow the correct path based on the condition result
  • Track all variable changes
  • Note all outputs

Example: Given a pseudocode segment with variables X, Y, and Z, complete the trace table showing values at each step.

3. Pseudocode Questions (Paper 2)

You may be asked to:

  • Write pseudocode to solve a given problem using conditional branching
  • Complete partially written pseudocode
  • Modify existing pseudocode to add or change functionality
  • Identify and correct errors in pseudocode

4. Flowchart Questions (Paper 2)

Flowchart questions test your ability to:

  • Convert pseudocode to flowcharts (and vice versa)
  • Identify symbols and their meanings
  • Trace through flowcharts to determine output
  • Complete incomplete flowcharts
Exam Success Tips
  • Read carefully: Always understand what the condition is checking before answering
  • Trace step by step: For trace tables, go through the code line by line
  • Check the path: Make sure you follow YES/TRUE or NO/FALSE correctly
  • Don't forget ENDIF: In pseudocode, every IF needs an ENDIF
  • Practice daily: The more pseudocode you write, the easier it becomes
11

CSEC Exam Practice Questions

Test yourself with these exam-style questions. Answers are provided at the end of each question.

Question 1: Multiple Choice

Which of the following is the correct syntax for an IF-THEN-ELSE statement?

  1. IF condition THEN statements ELSE statements
  2. IF condition THEN statements ELSE statements ENDIF
  3. IF condition THEN statements ENDIF ELSE statements
  4. IF condition THEN statements ELSE statements

Answer: B

IF condition THEN statements ELSE statements ENDIF

The ENDIF is required at the end of the entire IF-THEN-ELSE structure. Option B is correct.

Question 2: Multiple Choice

A variable called Temperature has a value of 30. What will be the output of the following pseudocode?

IF Temperature > 25 THEN
    OUTPUT "Hot"
ELSE
    OUTPUT "Cool"
ENDIF
  1. Hot
  2. Cool
  3. Hot Cool
  4. No output

Answer: A

Since 30 > 25 is TRUE, the THEN branch executes and outputs "Hot". The ELSE branch is skipped.

Question 3: Short Answer

State the difference between the AND and OR logical operators. Include a truth table in your answer.

Answer:

AND returns TRUE only if BOTH conditions are TRUE.

OR returns TRUE if AT LEAST ONE condition is TRUE.

A B A AND B A OR B
TRUE TRUE TRUE TRUE
TRUE FALSE FALSE TRUE
FALSE TRUE FALSE TRUE
FALSE FALSE FALSE FALSE

Question 4: Trace Table

Complete a trace table for the following pseudocode. Show the value of each variable at each step and the output.

1.  INPUT A
2.  INPUT B
3.  IF A > B THEN
4.      C = A + B
5.  ELSE
6.      C = A - B
7.  ENDIF
8.  OUTPUT C

Use input values A = 8, B = 5

Answer:

Line A B C Output
1 8 - - -
2 8 5 - -
3 Condition: 8 > 5 is TRUE, go to line 4
4 8 5 13 -
8 8 5 13 13

Question 5: Pseudocode Writing

Write pseudocode for a program that calculates the cost of a taxi fare based on the following rules:

  • Flag down rate: $50 (first 1 km)
  • Additional distance: $15 per km
  • Night surcharge: Add $25 if traveling after 11 PM

The program should input the distance traveled and the hour of the day (0-23), then output the total fare.

Sample Answer:

// Input distance in km and hour (0-23)
INPUT Distance
INPUT Hour

// Calculate base fare
IF Distance <= 1 THEN
    Fare = 50
ELSE
    AdditionalKM = Distance - 1
    Fare = 50 + (AdditionalKM * 15)
ENDIF

// Check for night surcharge
IF Hour >= 23 OR Hour < 5 THEN
    Fare = Fare + 25
    OUTPUT "Night surcharge applied"
ENDIF

// Output total fare
OUTPUT "Total fare: $", Fare

Question 6: Flowchart to Pseudocode

Convert the following flowchart description into pseudocode:

  • START
  • INPUT Score
  • Decision: Score ≥ 80?
  • If YES: OUTPUT "Grade A"
  • If NO: Decision: Score ≥ 60?
  • If YES: OUTPUT "Grade B"
  • If NO: OUTPUT "Grade C"
  • END

Answer:

// Converted from flowchart
INPUT Score

IF Score >= 80 THEN
    OUTPUT "Grade A"
ELSE
    IF Score >= 60 THEN
        OUTPUT "Grade B"
    ELSE
        OUTPUT "Grade C"
    ENDIF
ENDIF

Explanation: The flowchart shows a nested decision structure. If the first condition (Score ≥ 80) is false, we check the second condition (Score ≥ 60). Note that we check the higher score range first.

Question 7: Structured Question

A school cafeteria uses the following pricing system for lunch:

  • Students pay $80 for lunch
  • Teachers pay $120 for lunch
  • Visitors pay $150 for lunch

Write pseudocode that:

  1. Inputs the person's category (Student, Teacher, or Visitor)
  2. Inputs the number of lunches purchased
  3. Calculates and outputs the total cost

Answer:

// Cafeteria pricing system

// a) Input category and quantity
INPUT Category
INPUT Quantity

// b) Determine price per lunch and calculate total
IF Category = "Student" THEN
    PricePerLunch = 80
ELSE
    IF Category = "Teacher" THEN
        PricePerLunch = 120
    ELSE
        IF Category = "Visitor" THEN
            PricePerLunch = 150
        ENDIF
    ENDIF
ENDIF

// c) Calculate and output total cost
TotalCost = PricePerLunch * Quantity
OUTPUT "Total cost: $", TotalCost
12

Summary

Key Points to Remember
  • Conditional branching allows programs to make decisions based on conditions
  • Conditions are expressions that evaluate to TRUE or FALSE
  • Relational operators (=, ≠, <, >, ≤, ≥) compare values
  • Logical operators (AND, OR, NOT) combine conditions
  • IF-THEN executes code only when a condition is TRUE
  • IF-THEN-ELSE provides alternative code paths for TRUE and FALSE
  • ENDIF is required to close every IF block
  • Nested IFs handle multiple conditions in sequence
  • Flowcharts use diamonds for decisions and YES/NO paths
Keep Practicing!

Conditional branching is a fundamental skill that you'll use throughout your programming journey. The more you practice writing pseudocode and tracing through examples, the more natural it will become. Remember to always:

  • Match THEN and ELSE with their corresponding ENDIF
  • Check conditions from highest to lowest when dealing with ranges
  • Use proper indentation for readability
  • Test your code with different inputs to ensure it works correctly

CSEC Information Technology | Conditional Branching Study Guide

Study hard, practice daily, and success will follow!

Scroll to Top