Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Basics (retired) Operators Operator Precedence

Dov Breuer
Dov Breuer
8,268 Points

Someone please explain to me how this equals 20? let y = 25 - 5 * 2 + 5

I do not understand how come this equals 20

let y = 25 - 5 * 2 + 5 To me the results should be as follows: 5*2 = 10 10+5 = 15 15-25 = -10

What am i missing?

Jorge Solana
Jorge Solana
6,064 Points

Just think like a machine. Just get binary operations one by one, always reading from the beginning. So in that formula you say: 25 - 5 * 2 + 5, we always start to read from left looking for precedence operators in order like this:

25 - 5? No // 5 * 2? YES! (So do the math and don keep reading) // 10 + 5? No, so we don't find any more high level operators and have to go for the lower level ones...

25 - 10? Yes (So do the math and keep going) // 15 + 5? Yes (So do the math) // And no more instructions. So we got the final result: 20.

I just wanted to make it look more simple as Michael Chen used the minus operator in his explanation (which is of course valid too).

Hope it helps.

3 Answers

Ricothe Chen
Ricothe Chen
4,210 Points

since you multiply first you forgot the minus sign in front of 5, it should be -5*2 = -10, then you add up 5, which becomes -10+5 = -5, and you add 25, that leads to 25-5 = 20.

//by adding parenthesis in front of a minus symbol, it changes the symbol "+" --> "-" within 25 - 5 * 2 + 5 =25-10+5 = 20-(10-5) =25-5 =20

or

25-(5*2)+5</br> =25-10+5</br> =15+5</br> =20

P.E.M.D.A.S.

Simplest rule to remember : BODMAS

B : Brackets O : Parenthesis D : Division M: Multiplication A: Addition S: Subtraction

This is Highest to lowest precedence and left to right ... :)

So to answer your question :

25 - 5 * 2 + 5 = 25 - (5 * 2) + 5 = 25 - 10 + 5 = (25 -10) + 5 = 15 + 5 = 20