1
00:00:00,190 --> 00:00:05,481
Most programming languages like you
change math operations together and
2
00:00:05,481 --> 00:00:07,023
C# is no exception.
3
00:00:07,023 --> 00:00:12,180
The order of operations that you were
taught in math class supplies in C# too.
4
00:00:12,180 --> 00:00:15,313
If you didn't have order
of operations you'd
5
00:00:15,313 --> 00:00:17,971
assume that you add 1 to 2 getting 3.
6
00:00:17,971 --> 00:00:24,415
And then multiply 3 by 3 to get 9,
but that's not what we get.
7
00:00:24,415 --> 00:00:27,486
Instead, the result is 7.
8
00:00:27,486 --> 00:00:31,712
This is because of order of operations.
9
00:00:31,712 --> 00:00:34,953
In chain math operations,
multiplication and
10
00:00:34,953 --> 00:00:40,308
division operations always come first and
addition and subtraction second.
11
00:00:40,308 --> 00:00:45,179
C# respects this concept by following
something called operator precedents.
12
00:00:45,179 --> 00:00:45,804
That is,
13
00:00:45,804 --> 00:00:51,370
the evaluation of some operators precedes
the evaluation of some other operators.
14
00:00:51,370 --> 00:00:56,280
The multiplication and division operators
have higher precedents than addition and
15
00:00:56,280 --> 00:00:57,786
subtraction operators.
16
00:00:57,786 --> 00:01:02,304
So that's why when we evaluate 1 + 2 x 3,
we get 7 and not 9.
17
00:01:02,304 --> 00:01:08,706
The multiplication operator has higher
precedence than the addition operator.
18
00:01:08,706 --> 00:01:15,850
So we do the multiplication first giving
us 6, we then add 1 in 6 giving us 7.
19
00:01:15,850 --> 00:01:20,305
But suppose we wanted to ensure that
the addition operation occurs first.
20
00:01:20,305 --> 00:01:24,518
If we were working in a math textbook we'd
add parentheses around the operation to
21
00:01:24,518 --> 00:01:28,500
indicate it should go first, and
the multiplication should happen second.
22
00:01:28,500 --> 00:01:33,654
And that same notation works in C#,
C# will always evaluate math operations
23
00:01:33,654 --> 00:01:39,350
within parentheses first before it goes on
to evaluate the rest of the expression.
24
00:01:39,350 --> 00:01:43,407
So with the parentheses 1 + 2
is evaluated first giving 3.
25
00:01:45,770 --> 00:01:48,530
And then that's multiplied by 3 to give 9.
26
00:01:48,530 --> 00:01:52,555
If you're not comfortable with operator
presidence or you want to learn more,
27
00:01:52,555 --> 00:01:54,610
check the teachers notes for more info.