Expressions in Programming
Using Expressions
- What is a Variable?
- A variable is a named storage location in programming that can hold a value.
Characteristics of an Expression
- An expression is a combination of operators, literals (constants), and variables that computes a value.
- Operands: These are the values or variables that the operator acts upon.
- Operator: A symbol that performs a specific operation (e.g.,
*, /, +, etc.).
Types of Operators
- Arithmetic Operators
- Used for mathematical calculations.
- Common arithmetic operators:
+: Addition -: Subtraction *: Multiplication /: Division ^: Exponentiation %: Modulus (returns the remainder)//: Integer division (returns an integer quotient.)- Examples:
sngPrice * 0.25 (where sngPrice is a variable representing a number)
- Assignment Operators
- Used to assign values to variables.
- Types include:
=: Assign value (e.g., x = 6)+=: Add and assign (e.g., x += 6 which is equivalent to x = x + 6)-=: Subtract and assign (e.g., x -= 6)*=: Multiply and assign (e.g., x *= 6)/=: Divide and assign (e.g., x /= 6)- More specialized operators like
^= for exponentiation and &= for string concatenation.
- Relational Operators
- Compare two values and return a boolean result (true or false).
- Types include:
<: Less than (e.g., a < b)<=: Less than or equal to (e.g., a <= b)>: Greater than (e.g., a > b)>=: Greater than or equal to (e.g., a >= b)=: Equal to (e.g., a = b)<>: Not equal to (e.g., a <> b)
- Logical Operators
- Used to combine multiple relational expressions.
- Types include:
AND: Returns true if both conditions are true.OR: Returns true if at least one condition is true.NOT: Reverses the truth value.
Order of Precedence
- Refers to the rules determining the order in which operations should be performed in an expression:
- Parentheses
() - Exponentiation
^ - Multiplication
* and Division / - Addition
+ and Subtraction -
Practice Programs
- Program for Arithmetic Operations:
- Create a program that performs exponentiation, modulus division, and integer division on two inputted numbers.
- Relational and Logical Operators Program:
- Evaluate and illustrate the functions of comparison and logical operators using user input.
- Calculate Area, Perimeter, and Volume:
- Create a program that computes the area, perimeter, and volume of a square based on the input of the side length.
Test Your Knowledge
- Complete activities on pages 147 – 148 to reinforce knowledge.
- Engage in hands-on activities to practice concepts learned.