Swift: Arithmetic output

We have seen how to output the text, let’s now focus on numbers…

To recall (Swift: Types of variables – constants), we have seen that numbers can be declared either as integers, doubles or floats.

In Swift, as in any programming language, we can addition, subtract, multiply or divide numbers.

So let’s declare 2 variables as numbers and do some math…

var num1 : Int = 20

var num2 : Int = 4

var num3 : Double = 4.5

/* pay attention that you will either need to write a comma(,) or a point (.) – depending on your language setups */

Now, let’s take a look at the 5 basic arithmetic operations that you can perform in swift:

Addition (+)

print(num1 + num2) // output is 24

Substraction (-)

print(num1 – num2) // output is 16

Multiplication (*)

print(num1 * num2) // output is 80

Division (/)

print(num1 / num2) //output is 5

Remainder (%)

Print(num1 / num2) // output is 0

The logic behind remainder is the following: the program first computes how many times 4s will fit in the 20 (so here it is 5) and then it will give us the number which is left, that cannot be divided by 4 in order to give a whole number.

 

A last important remark, before moving forward is that we can use all these arithmetic operators only with variables that are of the same type. Indeed, if we try to multiply a whole number (for example the variable num1) with a double number (num3), we will incur an error

Screen Shot 2017-04-14 at 19.29.15.png

So to overcome this, we will need to declare the variable “num1” as a double also int the print function and this will resolve the issue

print(Double(num1) * num3) // output is 90

Screen Shot 2017-04-14 at 19.32.27.png

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: