Computer Science A · Programming fundamentals

Selection (if/else) and logic

Lesson 2

Selection (if/else) and logic

7 min read
AI Explain — Ask anything
AI Illustrate — Make it visual

Why This Matters

# Selection (if/else) and Logic - Summary This lesson covers conditional statements and Boolean logic, essential for controlling program flow in Java. Students learn to implement if, if-else, and nested conditionals, apply logical operators (&&, ||, !), and understand short-circuit evaluation and De Morgan's Laws. These concepts are fundamental for AP Computer Science A, appearing extensively in both multiple-choice questions and free-response problems requiring decision-making algorithms and complex conditional expressions.

Key Words to Know

01
Selection — The process where a computer chooses which code to run based on whether a condition is true or false.
02
If Statement — A programming structure that executes a block of code only if a specified condition is true.
03
Else Statement — A programming structure that executes a block of code if the condition in the preceding 'if' statement was false.
04
Condition — A statement or expression that evaluates to either true or false, used to make decisions in selection structures.
05
Boolean Expression — An expression that can only have one of two values: true or false, often used as conditions.
06
Logical AND (`&&`) — A logical operator that returns true only if both conditions it connects are true.
07
Logical OR (`||`) — A logical operator that returns true if at least one of the conditions it connects is true.
08
Logical NOT (`!`) — A logical operator that reverses the truth value of a condition (true becomes false, false becomes true).
09
Nested If — An 'if' statement placed inside another 'if' or 'else' statement, allowing for more complex decision-making.
10
If-Else If-Else Chain — A series of 'if' and 'else if' statements that check multiple conditions in order, executing the code block for the first true condition found.

Core Concepts & Theory

Selection statements allow programs to make decisions and execute different code paths based on conditions. This is fundamental to creating intelligent, responsive software.

Key Terms:

Conditional statements (if/else) evaluate Boolean expressions to determine program flow. An if statement executes code only when a condition is true. An else clause provides an alternative path when the condition is false. else if (or elif) allows testing multiple conditions sequentially.

Boolean expressions return true or false values. They use relational operators: == (equal to), != (not equal), > (greater than), < (less than), >= (greater than or equal), <= (less than or equal).

Logical operators combine multiple conditions:

  • AND (&& or and): Both conditions must be true
  • OR (|| or or): At least one condition must be true
  • NOT (! or not): Inverts the Boolean value

Truth Tables (essential for Cambridge exams):

ABA AND BA OR B
TTTT
TFFT
FTFT
FFFF

Nested selection places if statements inside others, enabling complex decision-making. The general syntax follows:

if (condition1)
    // code block
else if (condition2)
    // code block
else
    // default code

Order of evaluation matters: logical operators follow precedence (NOT > AND > OR). Use parentheses to control evaluation order explicitly.

Cambridge Note: Examiners expect precise use of terminology. "Selection" is preferred over "branching" or "decision-making" in formal answers.

Detailed Explanation with Real-World Examples

Selection statements mirror everyday decision-making. Think of a traffic light system: IF light is red THEN stop, ELSE IF light is amber THEN prepare to stop, ELSE (green) proceed. This nested logic ensures only one action occurs.

Real-World Application 1: Authentication Systems

When you log into a website, the system uses selection:

if (username correct AND password correct)
    grant access
else if (username correct AND password incorrect)
    display "wrong password"
else
    display "account not found"

The AND operator ensures both credentials validate. Using OR would create a security vulnerability—imagine granting access with just a correct username!

Real-World Application 2: E-commerce Discount Logic

Online stores calculate prices using nested selection:

if (customer is VIP)
    discount = 20%
else if (order total > £100)
    discount = 15%
else if (first purchase)
    discount = 10%
else
    discount = 0%

Notice the order matters: VIP status checks first, preventing customers getting lesser discounts.

Analogy: A Restaurant Menu Decision Tree

Selecting a meal follows logical steps: IF vegetarian THEN show veggie options, ELSE IF allergic to nuts THEN filter nut dishes, ELSE show full menu. Each condition narrows choices systematically.

Short-Circuit Evaluation optimizes performance: In A AND B, if A is false, B isn't checked (result must be false). In A OR B, if A is true, B isn't evaluated. This prevents errors: if (divisor != 0 AND number/divisor > 5) safely checks division by placing the guard condition first.

Memory Aid (MNEMONIC): "AND needs ALL, OR needs ONE" helps remember logical operator requirements.

Worked Examples & Step-by-Step Solutions

Example 1: Grade Boundary Calculator (6 marks)

Question: Write pseudocode that inputs a percentage mark and outputs a grade. A (≥70), B (60-69), C (50-59), D (40-49), F (<40).

Solution:

INPUT mark
IF mark >= 70 THEN
    OUTPUT "Grade A"
ELSE IF mark >= 60 THEN
    OUTPUT "Grade B"
ELSE IF mark >= 50 THEN
    OUTPUT "Grade C"
ELSE IF mark >= 40 THEN
    OUTPUT "Grade D"
ELSE
    OUTPUT "Grade F"
ENDIF

Examiner Note: Conditions check from highest to lowest—crucial! If reversed, mark 75 would match "≥40" first, incorrectly outputting "D". Award 2 marks for correct structure, 2 for accurate conditions, 2 for proper output.

Example 2: Leap Year Validator (8 marks)

Question: A year is a leap year if divisible by 4, EXCEPT century years must be divisible by 400. Write code for year 2024, 1900, 2000.

Solution:

python
year = int(input("Enter year: "))
if year % 400 == 0:
    print("Leap year")
elif year % 100 == 0:
    print("Not leap year")
elif year % 4 == 0:
    print("Leap year")
else:
    print("Not leap year")

Step-by-Step Logic:

  1. Check 400 divisibility first (handles 2000 ✓)
  2. Then 100 divisibility (catches 1900 ✗)
  3. Finally 4 divisibility (covers 2024 ✓)
  4. Order is critical!

Test Results: 2024→Leap, 1900→Not leap, 2000→Leap

Examiner Note: Award 3 marks for correct logic sequence, 2 for modulo operations, 2 for testing all paths, 1 for appropriate output. Common error: checking divisibility by 4 before exceptions.

Common Exam Mistakes & How to Avoid Them

Mistake 1: Confusing Assignment (=) with Comparison (==)

Why it happens: Mathematical notation uses single equals...

This section is locked

Cambridge Exam Technique & Mark Scheme Tips

Command Word Guidance:

"Write" (4-6 marks): Produce complete, syntactically correct code. Include variable decl...

This section is locked

2 more sections locked

Upgrade to Starter to unlock all study notes, audio listening, and more.

Exam Tips

  • 1.Always use `==` for comparison and `=` for assignment. This is a common source of errors on the exam.
  • 2.Pay close attention to curly braces `{}`! They define the blocks of code that belong to an `if`, `else`, or `else if` statement. Missing or extra braces can completely change how your code runs.
  • 3.Practice tracing `if-else if-else` chains with different input values. Remember that once a condition is met in an `else if` chain, the rest of the chain is skipped.
  • 4.Understand the difference between `&&` (AND) and `||` (OR) thoroughly. Draw truth tables if it helps you visualize when each operator results in true or false.
  • 5.When you see a `!` (NOT) operator, remember it flips the truth value. `!true` is `false`, and `!false` is `true`.
Ask Aria anything!

Your AI academic advisor