Upcoming SlideShare
×

# 03. operators and-expressions

170

Published on

03. Operators and Expressions

0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total Views
170
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
7
0
Likes
0
Embeds 0
No embeds

No notes for slide

### 03. operators and-expressions

1. 1. Operators and ExpressionsPerforming Simple Calculations with C#Svetlin NakovTelerik Corporationwww.telerik.com
2. 2. Table of Contents1. Operators in C# and Operator Precedence2. Arithmetic Operators3. Logical Operators4. Bitwise Operators5. Comparison Operators6. Assignment Operators7. Other Operators8. Implicit and ExplicitType Conversions9. Expressions2
3. 3. Operators in C#Arithmetic, Logical, Comparison, Assignment, Etc.
4. 4. What is an Operator? Operator is an operation performed over dataat runtime Takes one or more arguments (operands) Produces a new value Operators have precedence Precedence defines which will be evaluated first Expressions are sequences of operators andoperands that are evaluated to a single value4
5. 5. Operators in C# Operators in C# : Unary – take one operand Binary – take two operands Ternary (?:) – takes three operands Except for the assignment operators, allbinary operators are left-associative The assignment operators and theconditional operator (?:) are right-associative5
6. 6. Categories of Operators in C#Category OperatorsArithmetic + - * / % ++ --Logical && || ^ !Binary & | ^ ~ << >>Comparison == != < > <= >=Assignment= += -= *= /= %= &= |=^= <<= >>=String concatenation +Type conversion is as typeofOther . [] () ?: new6
7. 7. Operators Precedence
8. 8. Operators PrecedencePrecedence OperatorsHighest ()++ -- (postfix) new typeof++ -- (prefix) + - (unary) ! ~* / %+ -<< >>< > <= >= is as== !=&Lower ^8
9. 9. Operators Precedence (2)Precedence OperatorsHigher |&&||?:Lowest= *= /= %= += -= <<= >>= &= ^=|=9 Parenthesis operator always has highestprecedence Note: prefer using parentheses, even when itseems stupid to do so
10. 10. Arithmetic Operators
11. 11. Arithmetic Operators Arithmetic operators +, -, * are the same as inmath Division operator / if used on integers returnsinteger (without rounding) or exception Division operator / if used on real numbersreturns real number or Infinity or NaN Remainder operator % returns the remainderfrom division of integers The special addition operator ++ increments avariable11
12. 12. Arithmetic Operators – Example12int squarePerimeter = 17;double squareSide = squarePerimeter / 4.0;double squareArea = squareSide * squareSide;Console.WriteLine(squareSide); // 4.25Console.WriteLine(squareArea); // 18.0625int a = 5;int b = 4;Console.WriteLine( a + b ); // 9Console.WriteLine( a + b++ ); // 9Console.WriteLine( a + b ); // 10Console.WriteLine( a + (++b) ); // 11Console.WriteLine( a + b ); // 11Console.WriteLine(12 / 3); // 4Console.WriteLine(11 / 3); // 3
13. 13. Arithmetic Operators –Example (2)13Console.WriteLine(11.0 / 3); // 3.666666667Console.WriteLine(11 / 3.0); // 3.666666667Console.WriteLine(11 % 3); // 2Console.WriteLine(11 % -3); // 2Console.WriteLine(-11 % 3); // -2Console.WriteLine(1.5 / 0.0); // InfinityConsole.WriteLine(-1.5 / 0.0); // -InfinityConsole.WriteLine(0.0 / 0.0); // NaNint x = 0;Console.WriteLine(5 / x); // DivideByZeroException
14. 14. Arithmetic Operators –Overflow Examples14int bigNum = 2000000000;int bigSum = 2 * bigNum; // Integer overflow!Console.WriteLine(bigSum); // -294967296bigNum = Int32.MaxValue;bigNum = bigNum + 1;Console.WriteLine(bigNum); // -2147483648checked{// This will cause OverflowExceptionbigSum = bigNum * 2;}
15. 15. Arithmetic OperatorsLive Demo
16. 16. Logical Operators
17. 17. Logical Operators Logical operators take boolean operands andreturn boolean result Operator ! turns true to false and falseto true Behavior of the operators &&, || and ^(1 == true, 0 == false) :17Operation || || || || && && && && ^ ^ ^ ^Operand1 0 0 1 1 0 0 1 1 0 0 1 1Operand2 0 1 0 1 0 1 0 1 0 1 0 1Result 0 1 1 1 0 0 0 1 0 1 1 0
18. 18. Logical Operators – Example Using the logical operators:18bool a = true;bool b = false;Console.WriteLine(a && b); // FalseConsole.WriteLine(a || b); // TrueConsole.WriteLine(a ^ b); // TrueConsole.WriteLine(!b); // TrueConsole.WriteLine(b || true); // TrueConsole.WriteLine(b && true); // FalseConsole.WriteLine(a || true); // TrueConsole.WriteLine(a && true); // TrueConsole.WriteLine(!a); // FalseConsole.WriteLine((5>7) ^ (a==b)); // False
19. 19. Logical OperatorsLive Demo
20. 20. Bitwise Operators
21. 21. Bitwise Operators Bitwise operator ~ turns all 0 to 1 and all 1 to 0 Like ! for boolean expressions but bit by bit The operators |, & and ^ behave like ||, && and ^for boolean expressions but bit by bit The << and >> move the bits (left or right) Behavior of the operators|, & and ^:21Operation | | | | & & & & ^ ^ ^ ^Operand1 0 0 1 1 0 0 1 1 0 0 1 1Operand2 0 1 0 1 0 1 0 1 0 1 0 1Result 0 1 1 1 0 0 0 1 0 1 1 0
22. 22. Bitwise Operators (2) Bitwise operators are used on integer numbers(byte, sbyte, int, uint, long, ulong) Bitwise operators are applied bit by bit Examples:22ushort a = 3; // 00000000 00000011ushort b = 5; // 00000000 00000101Console.WriteLine( a | b); // 00000000 00000111Console.WriteLine( a & b); // 00000000 00000001Console.WriteLine( a ^ b); // 00000000 00000110Console.WriteLine(~a & b); // 00000000 00000100Console.WriteLine( a << 1); // 00000000 00000110Console.WriteLine( a >> 1); // 00000000 00000001
23. 23. Bitwise Operators –Tips &Tricks How to get the bit at position p in a number n? How to set the bit at position p to 0?23int p = 5;int n = 35; // 00000000 00100011int mask = 1 << p; // 00000000 00100000int nAndMask = n & mask; // 00000000 00100000int bit = nAndMask >> p; // 00000000 00000001Console.WriteLine(bit); // 1int p = 5;int n = 35; // 00000000 00100011int mask = ~(1 << p); // 11111111 11011111int result = n & mask; // 00000000 00000011Console.WriteLine(result); // 3
24. 24. Bitwise Operators –Tips &Tricks (2) How to set the bit at position p to 1? How to print a binary number to the console?24int p = 4;int n = 35; // 00000000 00100011int mask = 1 << p; // 00000000 00010000int result = n | mask; // 00000000 00110011Console.WriteLine(result); // 3Console.WriteLine(Convert.ToString(result, 2).PadLeft(32, 0));// 00000000000000000000000000110011
25. 25. Bitwise OperatorsLive Demo
26. 26. Comparison andAssignment Operators
27. 27. Comparison Operators Comparison operators are used to comparevariables ==, <, >, >=, <=, != Comparison operators example:27int a = 5;int b = 4;Console.WriteLine(a >= b); // TrueConsole.WriteLine(a != b); // TrueConsole.WriteLine(a == b); // FalseConsole.WriteLine(a == a); // TrueConsole.WriteLine(a != ++b); // FalseConsole.WriteLine(a > b); // False
28. 28. Assignment Operators Assignment operators are used to assign avalue to a variable , =, +=, -=, |=, ... Assignment operators example:28int x = 6;int y = 4;Console.WriteLine(y *= 2); // 8int z = y = 3; // y=3 and z=3Console.WriteLine(z); // 3Console.WriteLine(x |= 1); // 7Console.WriteLine(x += 3); // 10Console.WriteLine(x /= 2); // 5
29. 29. Comparison andAssignment OperatorsLive Demo
30. 30. Other Operators
31. 31. Other Operators String concatenation operator + is used toconcatenate strings If the second operand is not a string, it isconverted to string automatically31string first = "First";string second = "Second";Console.WriteLine(first + second);// FirstSecondstring output = "The number is : ";int number = 5;Console.WriteLine(output + number);// The number is : 5
32. 32. Other Operators (2) Member access operator . is used to accessobject members Square brackets [] are used with arraysindexers and attributes Parentheses ( ) are used to override thedefault operator precedence Class cast operator (type) is used to cast onecompatible type to another32
33. 33. Other Operators (3) Conditional operator ?: has the form(if b is true then the result is x else the result is y) The new operator is used to create new objects The typeof operator returns System.Typeobject (the reflection of a type) The is operator checks if an object iscompatible with given type33b ? x : y
34. 34. Other Operators Null-coalescing operator ?? is used to define adefault value for both nullable value types andreference types It returns the left-hand operand if it is not null Otherwise it returns the right operand34int? x = null;int y = x ?? -1;int? x = 1;int y = x ?? -1;Here the value of y is -1Here the value of y is 1
35. 35. Other Operators – Example Using some other operators:35int a = 6;int b = 4;Console.WriteLine(a > b ? "a>b" : "b>=a"); // a>bConsole.WriteLine((long) a); // 6int c = b = 3; // b=3; followed by c=3;Console.WriteLine(c); // 3Console.WriteLine(a is int); // TrueConsole.WriteLine((a+b)/2); // 4Console.WriteLine(typeof(int)); // System.Int32int d = new int();Console.WriteLine(d); // 0
36. 36. Other OperatorsLive Demo
37. 37. Implicit and ExplicitType Conversions
38. 38. ImplicitType Conversion Implicit type conversion Automatic conversion of value of one data typeto value of another data type Allowed when no loss of data is possible "Larger" types can implicitly take values ofsmaller "types" Example:38int i = 5;long l = i;
39. 39. ExplicitType Conversion Explicit type conversion Manual conversion of a value of one data typeto a value of another data type Allowed only explicitly by (type) operator Required when there is a possibility of loss ofdata or precision Example:39long l = 5;int i = (int) l;
40. 40. Type Conversions – Example Example of implicit and explicit conversions: Note: Explicit conversion may be used even ifnot required by the compiler40float heightInMeters = 1.74f; // Explicit conversiondouble maxHeight = heightInMeters; // Implicitdouble minHeight = (double) heightInMeters; // Explicitfloat actualHeight = (float) maxHeight; // Explicitfloat maxHeightFloat = maxHeight; // Compilation error!
41. 41. Type ConversionsLive Demo
42. 42. Expressions
43. 43. Expressions Expressions are sequences of operators,literals and variables that are evaluated tosome value Examples:43int r = (150-20) / 2 + 5; // r=70// Expression for calculation of circle areadouble surface = Math.PI * r * r;// Expression for calculation of circle perimeterdouble perimeter = 2 * Math.PI * r;
44. 44. Expressions (2) Expressions has: Type (integer, real, boolean, ...) Value Examples:44int a = 2 + 3; // a = 5int b = (a+3) * (a-4) + (2*a + 7) / 4; // b = 12bool greater = (a > b) || ((a == 0) && (b == 0));Expression of typeint. Calculated atcompile time.Expressionof type int.Calculatedat runtime.Expression of type bool.Calculated at runtime.
45. 45. ExpressionsLive Demo
46. 46. Summary We discussed the operators in C#: Arithmetic, logical, bitwise, comparison,assignment and others Bitwise calculations Operator precedence We learned when to use implicit and explicittype conversions We learned how to use expressions46
47. 47. Resources Boolean algebra (logic) http://en.wikipedia.org/wiki/Boolean_algebra_%28logic%29 Bitwise mask http://en.wikipedia.org/wiki/Mask_%28computing%29 Bitwise operation http://en.wikipedia.org/wiki/Bitwise_operation BitTwiddling Hacks graphics.stanford.edu/~seander/bithacks.html47