## Expressions

# Introduction

In computer programming, we are giving instructions to the computer to process. The instructions we give can be made up of different idioms. We have already looked at a few of these, such as initializing variables with values, and creating functions. We will now consider an idiom known as an **expression**. Expressions are used to evaluate into either, true, false, or a numeric value.

# What is an Expression?

An expression has three parts:

- Variable or Literal
- Operator
- Variable or Literal

For example:

```
a > 4
```

In this example, we have the three components of an expression:

**Variable**or Literal: In this case, the variable 'a'.**Operator**: In this case, the "greater than" operator.- Variable or
**Literal**: In this case, the numeric literal '4'.

Here is another example:

```
b == c
```

In this example, we have the three components of an expression:

**Variable**or Literal: In this case, the variable 'b'.**Operator**: In this case, the "equivalence" operator.**Variable**or Literal: In this case, the variable 'c'.

And here is a final example:

```
5 * 3
```

In this example, we have an arithmetic expression. Here, the three components of an expression are:

- Variable or
**Literal**: In this case, the literal '5'. **Operator**: In this case, the "equivalence" operator.- Variable or
**Literal**: In this case, the literal '3'.

# Operators

Operators are used to compare or transform the terms on either side of it. The operators are categorized into Algebraic, Comparative and Boolean Algebraic.

## Algebraic Operators

- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Modulus: %

**Note:** The modulus operator is very useful, yet often underutilized. For those unfamiliar with the modulus operation, it is used to return the remainder from a division. So, for example, 10 / 5 = 2 remainder 0, thus 10 % 5 is 0. If we look at 7 / 2 = 3 remainder 1, thus 7 % 2 is 1. Why is this useful? Well, for many reasons. One very useful situation is where you need to find out if a number is a factor of another number (this is referred to as a Factor). Another example for use is when you need to find even and odd numbers. So if you use x % 2, when this equates to 0, x is even, and when it equates to 1, x is odd.

## Comparison Operators

- Equivalence: ==
- Greater than: >
- Lesser than: <
- Inequality: !=
- Greater than or equal to: >=
- Lesser than or equal to: <=

## Boolean Algebraic Operators

- AND: and
- OR: or
- NOT: !
- XOR: ^

# Examples

**Algebraic**

```
1 + 2
b - 4
a * x
4 / 2
10 % 5
```

**Comparison**

```
a > 10
c < 1
5 == x
8 != d
```

**Boolean Algebraic**

```
1 and b
c or not d
1011 ^ 0101
```

# Exercises

Which of the following are NOT expressions, and why?

- x and y or z
- a % 10
- x = 1
- f(x) = 2 * x