Lesson 11Control Flow

If Statements

Making Decisions with If

The if statement lets your program make decisions. It runs code only when a condition is true!

Basic Syntax

if condition {
    // code to run
}

Comparison Operators

==

Equal

!=

Not equal

>

Greater

<

Less

>=

Greater/equal

<=

Less/equal

Logical Operators

&&

AND - Both must be true

||

OR - One must be true

!

NOT - Flips true/false

Real-World Example

Think of if like a traffic light: "If the light is green, then go!"

main.swift
// Basic if statement
let temperature = 25

if temperature > 30 {
    print("It's hot outside!")
}

// Checking a condition
let hasHomework = true

if hasHomework {
    print("Time to study!")
}

// Multiple conditions with AND (&&)
let age = 12
let hasPermission = true

if age >= 10 && hasPermission {
    print("You can play the game!")
}

// Multiple conditions with OR (||)
let isWeekend = true
let isHoliday = false

if isWeekend || isHoliday {
    print("No school today!")
}

// Negation with NOT (!)
let isRaining = false

if !isRaining {
    print("Let's go outside!")
}

// Comparing values
let score = 85

if score >= 80 {
    print("Great job!")
}

if score == 100 {
    print("Perfect score!")
}

Try It Yourself!

Write an if statement that checks if a student's grade is above 90 and prints "You got an A!"