Control Structures: Teaching Your Program to Make Decisions

What Are Control Structures?

Imagine you're giving directions to a friend. You don't just say "go straight forever" - you say things like "IF you see the red building, TURN LEFT" or "KEEP GOING UNTIL you reach the park." Control structures let your program make similar decisions!

The IF Statement: Your Program's First Decision

The IF statement is like a bouncer at a club - it checks if a condition is true before letting code execute.

graph TD A[Check Condition] --> B{Is it true?} B -->|Yes| C[Execute Code Block] B -->|No| D[Skip Code Block] C --> E[Continue Program] D --> E

Basic IF Statement Syntax

if (condition) {
    // Code runs ONLY if condition is true
    cout << "Condition was true!" << endl;
}

Real-World Example: Temperature Checker

int temperature = 75;

if (temperature > 70) {
    cout << "It's a warm day!" << endl;
    cout << "Perfect for outdoor activities." << endl;
}

if (temperature > 90) {
    cout << "It's very hot! Stay hydrated!" << endl;
}

The IF-ELSE Statement: Either This OR That

IF-ELSE is like a fork in the road - you MUST go one way or the other, never both!

IF-ELSE Decision Tree Age >= 18? Can Vote! Register today Too Young Wait a bit TRUE FALSE

IF-ELSE Example: Pass/Fail Grade

int score = 75;

if (score >= 60) {
    cout << "Congratulations! You passed!" << endl;
    cout << "Your score: " << score << endl;
} else {
    cout << "Sorry, you didn't pass." << endl;
    cout << "You need at least 60 to pass." << endl;
}

The IF-ELSE-IF Ladder: Multiple Choices

Sometimes life isn't just yes or no - it's multiple choice! The IF-ELSE-IF ladder handles multiple conditions.

Complete Grade Calculator Example

int score = 85;
char grade;

if (score >= 90) {
    grade = 'A';
    cout << "Excellent work!" << endl;
} else if (score >= 80) {
    grade = 'B';
    cout << "Good job!" << endl;
} else if (score >= 70) {
    grade = 'C';
    cout << "Satisfactory." << endl;
} else if (score >= 60) {
    grade = 'D';
    cout << "Needs improvement." << endl;
} else {
    grade = 'F';
    cout << "Please see your instructor." << endl;
}

cout << "Your grade is: " << grade << endl;

Nested IF Statements: Decisions Within Decisions

Like Russian nesting dolls, you can put IF statements inside other IF statements!

graph TD A[Is it weekend?] --> B{Yes} A --> C{No} B --> D[Is it raining?] D --> E{Yes} D --> F{No} E --> G[Stay home & read] F --> H[Go to the park] C --> I[Go to work/school]

Nested IF Example: Event Planning

bool isWeekend = true;
bool isRaining = false;
int temperature = 75;

if (isWeekend) {
    cout << "It's the weekend!" << endl;
    
    if (isRaining) {
        cout << "Stay inside and watch movies." << endl;
    } else {
        if (temperature > 70) {
            cout << "Perfect day for a picnic!" << endl;
        } else {
            cout << "Maybe visit a museum." << endl;
        }
    }
} else {
    cout << "It's a weekday - time for work/school!" << endl;
}

The Switch Statement: Multiple Choice Made Easy

When you have many specific values to check, SWITCH is like a more elegant multiple-choice answer sheet.

Switch Statement Syntax

int choice = 2;

switch (choice) {
    case 1:
        cout << "You ordered a hamburger!" << endl;
        break;
    case 2:
        cout << "You ordered pizza!" << endl;
        break;
    case 3:
        cout << "You ordered a salad!" << endl;
        break;
    case 4:
        cout << "You ordered pasta!" << endl;
        break;
    default:
        cout << "Invalid choice!" << endl;
        break;
}

Important: The Break Statement

Without 'break', switch cases "fall through" like dominoes!

Switch Fall-through Example With break: Case 1 Case 2 Case 3 Only Case 1 executes Without break: Case 1 Case 2 Case 3 All cases execute!

Ternary Operator: The Compact IF-ELSE

The ternary operator is like IF-ELSE compressed into one line - perfect for simple decisions!

Ternary Operator Examples

// Example 1: Simple assignment
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";

// Example 2: In output
int score = 85;
cout << "You " << (score >= 60 ? "passed" : "failed") << " the test!" << endl;

// Example 3: Calculating values
int items = 5;
double price = (items > 3) ? 9.99 : 12.99;

Practice Exercise: Adventure Game

Create Your Own Adventure!

Build a simple text adventure game where the player makes choices:

#include <iostream>
using namespace std;

int main() {
    int choice;
    
    cout << "=== The Mysterious Cave ===" << endl;
    cout << "You stand at the entrance of a dark cave." << endl;
    cout << "What do you do?" << endl;
    cout << "1. Enter the cave" << endl;
    cout << "2. Walk away" << endl;
    cout << "3. Call for help" << endl;
    cout << "Enter your choice (1-3): ";
    cin >> choice;
    
    // TODO: Use switch or if-else to handle choices
    // Each choice should lead to different outcomes
    
    return 0;
}
Solution Hint
switch (choice) {
    case 1:
        cout << "\nYou bravely enter the cave..." << endl;
        cout << "You find a treasure chest!" << endl;
        break;
    case 2:
        cout << "\nYou decide to play it safe." << endl;
        cout << "Maybe another day..." << endl;
        break;
    case 3:
        cout << "\nYou call out loudly." << endl;
        cout << "A friendly explorer appears to help!" << endl;
        break;
    default:
        cout << "\nThat's not a valid choice!" << endl;
}

Common Patterns and Best Practices

graph TD A[Control Structure Best Practices] --> B[Use braces even for single lines] A --> C[Keep conditions simple] A --> D[Avoid deep nesting] A --> E[Always include default in switch] B --> F["if (x > 0) {
count++;
}"] C --> G[Break complex conditions
into variables] D --> H[Consider using functions
for complex logic] E --> I[Handles unexpected values]

Debugging Tips: Common Control Structure Mistakes

Common Mistakes to Avoid Missing Braces if (x > 0) cout << "Positive"; x++; // Always runs! Assignment vs Comparison if (x = 5) // Wrong! if (x == 5) // Correct! Forgetting Break case 1: cout << "One"; // Missing break!

Challenge Exercise: Grade Report System

Advanced Challenge

Create a comprehensive grade reporting system that:

  1. Accepts a numeric grade (0-100)
  2. Validates the input (must be 0-100)
  3. Assigns a letter grade
  4. Determines if the student is on the honor roll (90+)
  5. Provides appropriate feedback
  6. Asks if they want to check another grade
Requirements Checklist

Real-World Application: ATM Machine

// Simplified ATM System
double balance = 1000.00;
int choice;
double amount;

cout << "=== Welcome to SimpleBank ATM ===" << endl;
cout << "1. Check Balance" << endl;
cout << "2. Withdraw" << endl;
cout << "3. Deposit" << endl;
cout << "4. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;

switch (choice) {
    case 1:
        cout << "Your balance is: $" << balance << endl;
        break;
        
    case 2:
        cout << "Enter withdrawal amount: $";
        cin >> amount;
        if (amount > balance) {
            cout << "Insufficient funds!" << endl;
        } else if (amount <= 0) {
            cout << "Invalid amount!" << endl;
        } else {
            balance -= amount;
            cout << "Dispensing $" << amount << endl;
            cout << "New balance: $" << balance << endl;
        }
        break;
        
    case 3:
        cout << "Enter deposit amount: $";
        cin >> amount;
        if (amount > 0) {
            balance += amount;
            cout << "Deposit successful!" << endl;
            cout << "New balance: $" << balance << endl;
        } else {
            cout << "Invalid amount!" << endl;
        }
        break;
        
    case 4:
        cout << "Thank you for using SimpleBank!" << endl;
        break;
        
    default:
        cout << "Invalid choice!" << endl;
}

Key Takeaways

graph LR A[Master Control Structures] --> B[Write Dynamic Programs] B --> C[Handle User Input] C --> D[Create Interactive Apps] D --> E[Build Amazing Software!]