TECHNOLOGY 

Published on

Study Guide: Logic in Programming

I. Introduction

• Processors excel at logical operations, which are fundamental to digital circuits.

• Programming languages provide operators for handling logic.

• Two main types of logical operators:

  • Bitwise Operators: Operate on individual bits of integers.
  • Boolean Operators: Operate on Boolean (true/false) values.

• Terminology varies across languages (e.g., C uses "logical" instead of "Boolean"). This guide will use "bitwise" and "Boolean."

II. Bitwise Operators

• Act on individual bits of integers.

• Result: an integer value.

• Perform logical operations (AND, OR, XOR, NOT) on the bits of integers in parallel.

• Operators (common in C and Python):

  • AND: &
  • OR: |
  • XOR: ^
  • NOT (complement): ~

Example (Python):

x = 5  # Binary: 0101
y = 3  # Binary: 0011
a = x & y  # Bitwise AND
b = x | y  # Bitwise OR

# a is 1 (0001 in binary)
# b is 7 (0111 in binary)

Explanation of Example

• AND: The result is 1 only when both corresponding bits are 1.

• 5 & 3:

0101
0011
----
0001 (1 in decimal)

• OR: The result is 1 if either corresponding bit (or both) is 1.

• 5 | 3:

0101
0011
----
0111 (7 in decimal)

III. Boolean Operators

• Work on Boolean values (true or false).

• Result: a Boolean value.

• Boolean values: represented differently in different languages (e.g., True or False in Python).

• Boolean variable: a named memory address holding a true or false value.

• Expressions can evaluate to true or false (e.g., item_cost > 5).

Boolean Operators:

• Perform logical operations (AND, OR, NOT) on Boolean values.

• Example: item_on_sale and item_cost > 5 (checks if both conditions are true).

Boolean Operation C Operator Python Operator
AND && and
OR || or
NOT ! not

Comparison Operators:

• Compare two values and evaluate to true or false.

Comparison Operation Operator
EQUALITY ==
NOT EQUAL !=
GREATER THAN >
LESS THAN <
GREATER THAN OR EQUAL >=
LESS THAN OR EQUAL <=

Important:

  • == (double equals) is for equality comparison (returns true/false).
  • = (single equals) is for assignment (sets a variable's value).
  • Example: x == 5 (is x equal to 5?) vs. x = 5 (set x to 5).
0 Comments