Welcome to the Swift Arithmetic Operators tutorial! In this lesson, we'll explore the essential arithmetic operators Swift offers. Let's dive in!
Arithmetic operators are symbols that Swift uses to perform mathematical operations on values. We'll learn about five types of arithmetic operators in Swift:
Let's see some examples of each operator.
Addition is used to combine two numbers.
var sum = 5 + 3
print("The sum is \(sum)") // Output: The sum is 8Subtraction is used to find the difference between two numbers.
var difference = 10 - 3
print("The difference is \(difference)") // Output: The difference is 7Multiplication is used to find the product of two numbers.
var product = 5 * 3
print("The product is \(product)") // Output: The product is 15Division is used to divide one number by another.
var quotient = 12 / 3
print("The quotient is \(quotient)") // Output: The quotient is 4Modulus operator gives the remainder after division.
var remainder = 12 % 3
print("The remainder is \(remainder)") // Output: The remainder is 0 (since 12 is divisible by 3)When multiple operators are used in an expression, Swift follows a specific order to evaluate them. This order is called precedence. Let's take a look at a complex example:
var result = 5 + 3 * 2
print("The result is \(result)") // Output: The result is 11 (first, Swift multiplies 3 * 2, then adds 5)š Note: To change the order of operations, use parentheses ().
var result = (5 + 3) * 2
print("The result is \(result)") // Output: The result is 20 (first, Swift adds 5 + 3, then multiplies by 2)Operator associativity determines how multiple operators of the same type are grouped in expressions. Swift follows the following rules for arithmetic operators:
For example:
var result = 5 + 3 + 2
print("The result is \(result)") // Output: The result is 10 (first, Swift adds 5 + 3, then adds 2)š Note: You can use parentheses to explicitly group terms, like so:
var result = (5 + 3) + 2
print("The result is \(result)") // Output: The result is 10 (first, Swift adds 5 + 3, then adds 2)šÆ Practice time! Let's solve a few problems with arithmetic operators.
What is the result of the following code?
What is the remainder when 17 is divided by 4?
That's all for now! In the next lesson, we'll explore comparison operators in Swift. Keep practicing, and happy coding! š