Arithmetic Operators in Swift

The arithmetic operators are used to perform basic mathematical operations on numbers in Swift. These operators include the following:

  • Addition (+): Adds two numbers together.
  • Subtraction (-): Subtracts one number from another.
  • Multiplication (*): Multiplies two numbers together.
  • Division (/): Divides one number by another.
  • Remainder (%): Calculates the remainder of dividing one number by another.

Here are some examples of how you could use these operators in Swift:

let a = 5 
let b = 2 

let c = a + b  // c = 7 

let d = a - b  // d = 3 

let e = a * b  // e = 10 

let f = a / b  // f = 2.5 

let g = a % b  // g = 1

In this code, the a and b variables are declared and initialized with the values 5 and 2, respectively. Then, the arithmetic operators are used to perform various operations on these values and store the results in new variables.

For example, the + operator is used to add a and b together, and the result is stored in the c variable. Similarly, the - operator is used to subtract b from a, and the result is stored in the d variable.

The arithmetic operators in Swift work with both integer and floating-point numbers, and they can be used in a wide range of mathematical and computational tasks.


Posted

in