Understanding Logical Operators in Programming

Sep 23, 2024

Introduction to Logical Operators

Overview

  • Logical operators allow us to connect and modify Boolean expressions.
  • Types of logical operators:
    • Not operator
    • And operator
    • Or operator

Not Operator

  • Represented by an exclamation point (!).
  • Function: Gives the opposite of a Boolean expression.
    • If x is true, not x is false.
    • If x is false, not x is true.

And Operator

  • Represented by two ampersands (&&).
  • Function: Returns true only if both expressions are true.
    • x && y is true if both x is true and y is true.
    • Otherwise, it is false.

Or Operator

  • Represented by two vertical lines (||).
  • Function: Returns true if at least one expression is true.
    • x || y is true if either x or y is true, or both.
    • It is false only if both x and y are false.

Example: Not Operator

  • Declare a Boolean variable lightOn and set it to true.
  • When not operator is applied:
    • The value of lightOn is switched to false.

Code Example

  • Initial State:
    boolean lightOn = true;
    print(lightOn); // Outputs: true
    
  • After Applying Not:
    lightOn = !lightOn;
    print(lightOn); // Outputs: false
    
  • Repeating Process:
    • Switches back to true if not is applied again.

Practice

  • Encouragement to write programs using and, or, and not operators to reinforce understanding.