Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Math1:54 with Jeremy McLain
We'll learn about C#'s arithmetic operators.
Arithmetic Order of Operations:
() Inner most parenthesis first and from left to right
/ * % From left to right
+ - From left to right
We just saw the use of arithmetic in code for the first time.
Of course, C sharp can do more than just addition.
You can do anything a basic calculator can do.
There's subtraction, there's multiplication, there's division.
There's also an operator called modulus.
The modulus operator returns the remainder of a division operation.
You can also combine these operations together in a single line.
As you can see, the result of this expression is 6.
When you combine a bunch of operations together like this,
you need to be very careful about what order the operations are performed in.
Some operators have higher precedence than others, and
they are performed first even if they aren't first on the line.
In C sharp this works exactly like the arithmetic you learned in school.
Multiplication, division, and modulus are performed first.
If you have multiple multiplication, division, or modulus operators in a row
like we do here, then they're performed left to right.
Then addition and subtraction are performed, again from left to right.
So in our expression here, we first do 3 times 7.
Then we divide the result of that by 3.
Then we take the modulus of that, that gives us 1.
Then we add 5 and 2 together and subtract 1 and we get 6.
Now what if we wanted the 2- 3 to happen first?
Just like in arithmetic, we can use parentheses for that.
Parentheses have the highest precedence, so
whatever is inside them will get evaluated first.
If we wanted the addition to happen next, we could add more parentheses like this.
The innermost parentheses have the highest precedence,
so what's in them will always get evaluated first.
We don't all encounter long arithmetic like this every day.
Sometimes, I have to stop and think about it.
I'll include the order of operation rules in the teacher's notes for your reference.
You need to sign up for Treehouse in order to download course files.Sign up