Introduction to Computer Algorithm: Data Structures, Complexity, and Optimization for Modern AI Systems

Real-World Applications: Decision Making in Action

Section 6

Making Decisions: Conditional Statements (If, Else If, Else)

Introduction to Computer Algorithm: Data Structures, Complexity, and Optimization for Modern AI SystemsMaking Decisions: Conditional Statements (If, Else If, Else)

Conditional statements are the building blocks of decision-making in computer programs. They allow our code to react differently based on whether a certain condition is true or false. Think of it like this: if it's raining, take an umbrella; otherwise, leave it at home. This simple logic is what powers countless features we use every day.

Let's explore some real-world scenarios where conditional statements are indispensable:

  1. E-commerce and Pricing: Online stores use conditionals to offer discounts. If a customer has a coupon code, apply the discount; otherwise, charge the full price. They can also use conditionals to determine shipping costs based on the order total or destination.
let price = 100;
let hasCoupon = true;
let finalPrice;

if (hasCoupon) {
  finalPrice = price * 0.9; // 10% discount
} else {
  finalPrice = price;
}

console.log('The final price is: $' + finalPrice);
  1. User Authentication: When you log into a website or app, conditionals are at play. If the username and password match the stored credentials, grant access; otherwise, show an error message.
let enteredUsername = 'user123';
let storedUsername = 'user123';
let enteredPassword = 'password123';
let storedPassword = 'password123';

if (enteredUsername === storedUsername && enteredPassword === storedPassword) {
  console.log('Login successful! Welcome!');
} else {
  console.log('Invalid username or password. Please try again.');
}
  1. Game Development: Games are rife with conditional logic. For instance, if a player's health drops to zero, the game ends. If a player collects a certain number of coins, they level up. If the player presses the jump button, make the character jump.
graph TD;
    A[Player health > 0] --> B{Player presses jump button?};
    B -- Yes --> C[Character jumps];
    B -- No --> D[Character stays put];
    C --> E[Update character position];
    D --> E;
    E --> F{Game over condition met?};
    F -- Yes --> G[End Game];
    F -- No --> A;
チャプターへ戻る