Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
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
Start REPL: csharp
Quit REPL: quit

0:00
We just saw the use of arithmetic in code for the first time.

0:03
Of course, C sharp can do more than just addition.

0:06
You can do anything a basic calculator can do.

0:07
There's subtraction, there's multiplication, there's division.

0:14
There's also an operator called modulus.

0:17
The modulus operator returns the remainder of a division operation.

0:21
You can also combine these operations together in a single line.

0:26
As you can see, the result of this expression is 6.

0:29
When you combine a bunch of operations together like this,

0:32
you need to be very careful about what order the operations are performed in.

0:36
Some operators have higher precedence than others, and

0:39
they are performed first even if they aren't first on the line.

0:43
In C sharp this works exactly like the arithmetic you learned in school.

0:47
Multiplication, division, and modulus are performed first.

0:51
If you have multiple multiplication, division, or modulus operators in a row

0:56
like we do here, then they're performed left to right.

0:59
Then addition and subtraction are performed, again from left to right.

1:03
So in our expression here, we first do 3 times 7.

1:07
Then we divide the result of that by 3.

1:10
Then we take the modulus of that, that gives us 1.

1:14
Then we add 5 and 2 together and subtract 1 and we get 6.

1:20
Now what if we wanted the 2 3 to happen first?

1:23
Just like in arithmetic, we can use parentheses for that.

1:27
Parentheses have the highest precedence, so

1:29
whatever is inside them will get evaluated first.

1:33
If we wanted the addition to happen next, we could add more parentheses like this.

1:38
The innermost parentheses have the highest precedence,

1:41
so what's in them will always get evaluated first.

1:45
We don't all encounter long arithmetic like this every day.

1:48
Sometimes, I have to stop and think about it.

1:51
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