46
Operators and Operators and Expressions Expressions Performing Simple Calculations with C# Performing Simple Calculations with C# Svetlin Nakov Svetlin Nakov Telerik Telerik Corporation Corporation www.telerik. com

03. Operators, Expressions and Statements

Embed Size (px)

DESCRIPTION

Operators in C# Operators Precedence Arithmetic Operators String Concatenation Operators Logical Operators Bitwise Operators Comparison and Assignment Operators The Lambda Operator => and Lambda Expressions Other Operators Implicit and Explicit Type Conversion Expressions and Statements Exercises: Working with Operators and Expressions

Citation preview

Page 1: 03. Operators, Expressions and Statements

Operators and Operators and ExpressionsExpressions

Performing Simple Calculations with C#Performing Simple Calculations with C#

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: 03. Operators, Expressions and Statements

Table of ContentsTable of Contents

1.1. Operators in C# and Operator Operators in C# and Operator PrecedencePrecedence

2.2. Arithmetic OperatorsArithmetic Operators

3.3. Logical OperatorsLogical Operators

4.4. Bitwise OperatorsBitwise Operators

5.5. Comparison OperatorsComparison Operators

6.6. Assignment OperatorsAssignment Operators

7.7. Other OperatorsOther Operators

8.8. Implicit and Explicit Type ConversionsImplicit and Explicit Type Conversions

9.9. ExpressionsExpressions2

Page 3: 03. Operators, Expressions and Statements

Operators in C#Operators in C#Arithmetic, Logical, Comparison, Arithmetic, Logical, Comparison,

Assignment, Etc.Assignment, Etc.

Page 4: 03. Operators, Expressions and Statements

What is an OperatorWhat is an Operator??

OperatorOperator is an operation performed is an operation performed over data at runtimeover data at runtime Takes one or more arguments Takes one or more arguments

(operands)(operands)

Produces a new valueProduces a new value Operators have precedenceOperators have precedence

Precedence defines which will be Precedence defines which will be evaluated firstevaluated first

Expressions Expressions are sequences of are sequences of operators and operands that are operators and operands that are evaluated to a single valueevaluated to a single value 4

Page 5: 03. Operators, Expressions and Statements

Operators in C#Operators in C#

Operators in C# :Operators in C# : Unary – take one operandUnary – take one operand

Binary – take two operandsBinary – take two operands

Ternary (Ternary (?:?:) – takes three operands) – takes three operands Except for the assignment Except for the assignment

operators, all binary operators are operators, all binary operators are left-associativeleft-associative

The assignment operators and the The assignment operators and the conditional operator (conditional operator (?:?:) are right-) are right-associativeassociative

5

Page 6: 03. Operators, Expressions and Statements

Categories of Operators Categories of Operators in C#in C#

6

CategoryCategory OperatorsOperatorsArithmeticArithmetic ++ -- ** // %% ++++ ----LogicalLogical &&&& |||| ^ ! ^ !BinaryBinary && || ^̂ ~~ <<<< >>>>ComparisonComparison ==== !=!= << >> <=<= >=>=

AssignmentAssignment == +=+= -=-= *=*= /=/= %=%= &=&= ||== ^=^= <<=<<= >>=>>=

String String concatenationconcatenation ++

Type Type conversionconversion is as typeofis as typeof

OtherOther . [] () ?: new. [] () ?: new

Page 7: 03. Operators, Expressions and Statements

Operators Operators PrecedencePrecedence

Page 8: 03. Operators, Expressions and Statements

Operators PrecedenceOperators Precedence

8

PrecedePrecedencence OperatorsOperators

HighestHighest ++ --++ -- (postfix) (postfix) new typeof new typeof++ --++ -- (prefix) (prefix) + - + - (unary)(unary) ! ~ ! ~* / %* / %

+ -+ -

<< >><< >>

< > <= >= is as< > <= >= is as

== != == !=

&&

LowerLower ^̂

Page 9: 03. Operators, Expressions and Statements

Operators Precedence Operators Precedence (2)(2)

9

PrecedePrecedencence OperatorsOperators

HigherHigher ||&&&&

||||

?:?:

LowestLowest = *= /= %= += -= <<= >>= = *= /= %= += -= <<= >>= &= ^= |=&= ^= |= Parenthesis operator always has Parenthesis operator always has

highest precedencehighest precedence Note: prefer using Note: prefer using parenthesesparentheses, even , even

when it seems stupid to do sowhen it seems stupid to do so

Page 10: 03. Operators, Expressions and Statements

Arithmetic Arithmetic OperatorsOperators

Page 11: 03. Operators, Expressions and Statements

Arithmetic OperatorsArithmetic Operators Arithmetic operators Arithmetic operators ++,, --, , ** are the are the

same as in math same as in math Division operator Division operator // if used on integers if used on integers

returns integer (without rounding) or returns integer (without rounding) or exceptionexception

Division operator Division operator // if used on real if used on real numbers returns real number or numbers returns real number or InfinityInfinity or or NaNNaN

Remainder operatorRemainder operator %% returns the returns the remainder from division of integersremainder from division of integers

The special addition operator The special addition operator ++++ increments a variableincrements a variable 11

Page 12: 03. Operators, Expressions and Statements

Arithmetic Operators – Arithmetic Operators – ExampleExample

int squarePerimeter = 17;int squarePerimeter = 17;double squareSide = squarePerimeter/4.0;double squareSide = squarePerimeter/4.0;double squareArea = squareSide*squareSide;double squareArea = squareSide*squareSide;Console.WriteLine(squareSide); // 4.25Console.WriteLine(squareSide); // 4.25Console.WriteLine(squareArea); // 18.0625Console.WriteLine(squareArea); // 18.0625

int a = 5;int a = 5;int b = 4;int b = 4;Console.WriteLine( a + b ); // 9Console.WriteLine( a + b ); // 9Console.WriteLine( a + b++ ); // 9Console.WriteLine( a + b++ ); // 9Console.WriteLine( a + b ); // 10Console.WriteLine( a + b ); // 10Console.WriteLine( a + (++b) ); // 11Console.WriteLine( a + (++b) ); // 11Console.WriteLine( a + b ); // 11Console.WriteLine( a + b ); // 11

Console.WriteLine(11 / 3); // 3Console.WriteLine(11 / 3); // 3Console.WriteLine(11 % 3); // 2Console.WriteLine(11 % 3); // 2Console.WriteLine(12 / 3); // 4Console.WriteLine(12 / 3); // 4

12

Page 13: 03. Operators, Expressions and Statements

Arithmetic Arithmetic OperatorsOperatorsLive DemoLive Demo

Page 14: 03. Operators, Expressions and Statements

Logical Logical OperatorsOperators

Page 15: 03. Operators, Expressions and Statements

Logical OperatorsLogical Operators Logical operators take boolean Logical operators take boolean

operands and return boolean resultoperands and return boolean result Operator Operator !! turns turns truetrue to to falsefalse and and falsefalse toto truetrue

Behavior of the operators Behavior of the operators &&&&, , |||| and and ^̂ ((11 == == truetrue, , 00 == == falsefalse) :) :OperatiOperationon |||| |||| |||| |||| &&&& &&&& &&&& &&&& ^̂ ^̂ ^̂ ^̂

OperanOperand1d1 00 00 11 11 00 00 11 11 00 00 11 11

OperanOperand2d2 00 11 00 11 00 11 00 11 00 11 00 11

ResultResult 00 11 11 11 00 00 00 11 00 11 11 00

15

Page 16: 03. Operators, Expressions and Statements

Logical Operators – Logical Operators – ExampleExample

Using the logical operators:Using the logical operators:

bool a = true;bool a = true;bool b = false;bool b = false;Console.WriteLine(a && b); // FalseConsole.WriteLine(a && b); // FalseConsole.WriteLine(a || b); // TrueConsole.WriteLine(a || b); // TrueConsole.WriteLine(a ^ b); // TrueConsole.WriteLine(a ^ b); // TrueConsole.WriteLine(!b); // TrueConsole.WriteLine(!b); // TrueConsole.WriteLine(b || true); // TrueConsole.WriteLine(b || true); // TrueConsole.WriteLine(b && true); // FalseConsole.WriteLine(b && true); // FalseConsole.WriteLine(a || true); // TrueConsole.WriteLine(a || true); // TrueConsole.WriteLine(a && true); // TrueConsole.WriteLine(a && true); // TrueConsole.WriteLine(!a); // FalseConsole.WriteLine(!a); // FalseConsole.WriteLine((5>7) ^ (a==b)); // FalseConsole.WriteLine((5>7) ^ (a==b)); // False

16

Page 17: 03. Operators, Expressions and Statements

Logical Logical OperatorsOperators

Live DemoLive Demo

Page 18: 03. Operators, Expressions and Statements

Bitwise Bitwise OperatorsOperators

Page 19: 03. Operators, Expressions and Statements

Bitwise operator Bitwise operator ~~ turns all turns all 00 to to 11 and and all all 11 to to 00 Like Like !! for boolean expressions but bit for boolean expressions but bit

by bitby bit The operators The operators ||,, && and and ^̂ behave like behave like ||||,, &&&& and and ^̂ for boolean expressions for boolean expressions but bit by bitbut bit by bit

The The <<<< and and >>>> move the bits (left or move the bits (left or right)right)

Behavior of the operatorsBehavior of the operators||,, && and and ^̂::

OperatioOperationn || || || || && && && && ^̂ ^̂ ^̂ ^̂

Operand1Operand1 00 00 11 11 00 00 11 11 00 00 11 11

Operand2Operand2 00 11 00 11 00 11 00 11 00 11 00 11

ResultResult 00 11 11 11 00 00 00 11 00 11 11 0019

Page 20: 03. Operators, Expressions and Statements

Bitwise Operators (2)Bitwise Operators (2) Bitwise operators are used on Bitwise operators are used on

integer numbers (integer numbers (bytebyte, , sbytesbyte, , intint, , uintuint, , longlong, , ulongulong))

Bitwise operators are applied bit Bitwise operators are applied bit by bitby bit

Examples:Examples:ushort a = 3; // 00000000 00000011ushort a = 3; // 00000000 00000011ushort b = 5; // 00000000 00000101ushort b = 5; // 00000000 00000101Console.WriteLine( a | b); // 00000000 00000111Console.WriteLine( a | b); // 00000000 00000111Console.WriteLine( a & b); // 00000000 00000001Console.WriteLine( a & b); // 00000000 00000001Console.WriteLine( a ^ b); // 00000000 00000110Console.WriteLine( a ^ b); // 00000000 00000110Console.WriteLine(~a & b); // 00000000 00000100Console.WriteLine(~a & b); // 00000000 00000100Console.WriteLine( a<<1 ); // 00000000 00000110Console.WriteLine( a<<1 ); // 00000000 00000110Console.WriteLine( a>>1 ); // 00000000 00000001Console.WriteLine( a>>1 ); // 00000000 00000001

20

Page 21: 03. Operators, Expressions and Statements

Bitwise Bitwise OperatorsOperators

Live DemoLive Demo

Page 22: 03. Operators, Expressions and Statements

Comparison and Comparison and Assignment Assignment OperatorsOperators

Page 23: 03. Operators, Expressions and Statements

Comparison OperatorsComparison Operators Comparison operators are used to Comparison operators are used to

compare variablescompare variables ====,, <<,, >>,, >=>=,, <=<=,, !=!=

Comparison operators example:Comparison operators example:

int a = 5;int a = 5;int b = 4;int b = 4;Console.WriteLine(a >= b); // TrueConsole.WriteLine(a >= b); // TrueConsole.WriteLine(a != b); // TrueConsole.WriteLine(a != b); // TrueConsole.WriteLine(a == b); // FalseConsole.WriteLine(a == b); // FalseConsole.WriteLine(a == a); // TrueConsole.WriteLine(a == a); // TrueConsole.WriteLine(a != ++b); // FalseConsole.WriteLine(a != ++b); // FalseConsole.WriteLine(a > b); // FalseConsole.WriteLine(a > b); // False

23

Page 24: 03. Operators, Expressions and Statements

Assignment OperatorsAssignment Operators

Assignment operators are used to Assignment operators are used to assign a value to a variable ,assign a value to a variable , ==,, +=+=,, -=-=,, |=|=,, ......

Assignment operators example:Assignment operators example:

int x = 6;int x = 6;int y = 4;int y = 4;Console.WriteLine(y *= 2); // 8Console.WriteLine(y *= 2); // 8int z = y = 3; // y=3 and z=3 int z = y = 3; // y=3 and z=3 Console.WriteLine(z); // 3Console.WriteLine(z); // 3Console.WriteLine(x |= 1); // 7Console.WriteLine(x |= 1); // 7Console.WriteLine(x += 3); // 10Console.WriteLine(x += 3); // 10Console.WriteLine(x /= 2); // 5Console.WriteLine(x /= 2); // 5

24

Page 25: 03. Operators, Expressions and Statements

Comparison and Comparison and Assignment Assignment OperatorsOperators

Live DemoLive Demo

Page 26: 03. Operators, Expressions and Statements

Other OperatorsOther Operators

Page 27: 03. Operators, Expressions and Statements

Other OperatorsOther Operators String concatenation operator String concatenation operator ++ is is

used to concatenate strings used to concatenate strings If the second operand is not a If the second operand is not a

string, it is converted to string string, it is converted to string automaticallyautomatically

string first = "First";string first = "First";string second = "Second";string second = "Second";Console.WriteLine(first + second); Console.WriteLine(first + second); // FirstSecond// FirstSecondstring output = "The number is : ";string output = "The number is : ";int number = 5;int number = 5;Console.WriteLine(output + number);Console.WriteLine(output + number);// The number is : 5// The number is : 5

27

Page 28: 03. Operators, Expressions and Statements

Other Operators (2)Other Operators (2) Member access operator Member access operator .. is used is used

to access object membersto access object members Square brackets Square brackets [][] are used with are used with

arrays indexers and attributesarrays indexers and attributes ParenthesesParentheses (( )) are used to are used to

override the default operator override the default operator precedenceprecedence

Class cast operator Class cast operator (type)(type) is used is used to cast one compatible type to to cast one compatible type to anotheranother

28

Page 29: 03. Operators, Expressions and Statements

Other Operators (3)Other Operators (3) Conditional operator Conditional operator ?:?: has the form has the form

(if (if bb is true then the result is is true then the result is xx else the else the result is result is yy))

The The newnew operator is used to create new operator is used to create new objects objects

The The typeoftypeof operator returns operator returns System.TypeSystem.Type object (the reflection of a object (the reflection of a type)type)

The The isis operator checks if an object is operator checks if an object is compatible with given typecompatible with given type

b ? x : yb ? x : y

29

Page 30: 03. Operators, Expressions and Statements

Other Operators – Other Operators – ExampleExample

Using some other operators:Using some other operators:

int a = 6;int a = 6;int b = 4;int b = 4;Console.WriteLine(a > b ? "a>b" : "b>=a"); // a>bConsole.WriteLine(a > b ? "a>b" : "b>=a"); // a>bConsole.WriteLine((long) a); // 6Console.WriteLine((long) a); // 6

int c = b = 3; // b=3; followed by c=3;int c = b = 3; // b=3; followed by c=3;Console.WriteLine(c); // 3Console.WriteLine(c); // 3Console.WriteLine(a is int); // TrueConsole.WriteLine(a is int); // TrueConsole.WriteLine((a+b)/2); // 4Console.WriteLine((a+b)/2); // 4Console.WriteLine(typeof(int)); // System.Int32Console.WriteLine(typeof(int)); // System.Int32

int d = new int();int d = new int();Console.WriteLine(d); // 0Console.WriteLine(d); // 0

30

Page 31: 03. Operators, Expressions and Statements

Other OperatorsOther OperatorsLive DemoLive Demo

Page 32: 03. Operators, Expressions and Statements

Implicit and Implicit and Explicit Type Explicit Type ConversionsConversions

Page 33: 03. Operators, Expressions and Statements

Implicit Type Implicit Type ConversionConversion

Implicit Type ConversionImplicit Type Conversion Automatic conversion of value of Automatic conversion of value of

one data type to value of another one data type to value of another data typedata type

Allowed when no loss of data is Allowed when no loss of data is possiblepossible

"Larger" types can implicitly take "Larger" types can implicitly take values of smaller "types"values of smaller "types"

Example:Example:int i = 5;int i = 5;long l = i;long l = i;

33

Page 34: 03. Operators, Expressions and Statements

Explicit Type Explicit Type ConversionConversion

Explicit type conversionExplicit type conversion Manual conversion of a value of one Manual conversion of a value of one

data type to a value of another data data type to a value of another data typetype

Allowed only explicitly by Allowed only explicitly by (type)(type) operatoroperator

Required when there is a possibility Required when there is a possibility of loss of data or precisionof loss of data or precision

Example:Example:long l = 5;long l = 5;int i = (int) l;int i = (int) l;

34

Page 35: 03. Operators, Expressions and Statements

Type Conversions – Type Conversions – ExampleExample

Example of implicit and explicit Example of implicit and explicit conversions:conversions:

Note: Explicit conversion may be Note: Explicit conversion may be used even if not required by the used even if not required by the compilercompiler

float heightInMeters = 1.74f; // Explicit float heightInMeters = 1.74f; // Explicit conversionconversiondouble maxHeight = heightInMeters; // Implicitdouble maxHeight = heightInMeters; // Implicit

double minHeight = (double) heightInMeters; // double minHeight = (double) heightInMeters; // ExplicitExplicit

float actualHeight = (float) maxHeight; // float actualHeight = (float) maxHeight; // ExplicitExplicit

float maxHeightFloat = maxHeight; // Compilation float maxHeightFloat = maxHeight; // Compilation error!error!

35

Page 36: 03. Operators, Expressions and Statements

Type ConversionsType ConversionsLive DemoLive Demo

Page 37: 03. Operators, Expressions and Statements

ExpressionsExpressions

Page 38: 03. Operators, Expressions and Statements

ExpressionsExpressions

Expressions are sequences of Expressions are sequences of operators, literals and variables operators, literals and variables that are evaluated to some valuethat are evaluated to some value

Examples:Examples:

int r = (150-20) / 2 + 5; // r=70int r = (150-20) / 2 + 5; // r=70

// Expression for calculation of circle area// Expression for calculation of circle areadouble surface = Math.PI * r * r;double surface = Math.PI * r * r;

// Expression for calculation of circle // Expression for calculation of circle perimeterperimeterdouble perimeter = 2 * Math.PI * r;double perimeter = 2 * Math.PI * r;

38

Page 39: 03. Operators, Expressions and Statements

Expressions (2)Expressions (2)

Expressions has:Expressions has: Type (integer, real, boolean, ...)Type (integer, real, boolean, ...) ValueValue

Examples:Examples:

int a = 2 + 3; // a = 5int a = 2 + 3; // a = 5int b = (a+3) * (a-4) + (2*a + 7) / 4; // b = int b = (a+3) * (a-4) + (2*a + 7) / 4; // b = 1212bool greater = (a > b) || ((a == 0) && (b == bool greater = (a > b) || ((a == 0) && (b == 0));0));

Expression of Expression of type type intint. .

Calculated at Calculated at compile time.compile time.

ExpressiExpression of on of

type type intint. . CalculateCalculate

d at d at runtime.runtime.

Expression of Expression of type type boolbool. .

Calculated at Calculated at runtime.runtime.

39

Page 40: 03. Operators, Expressions and Statements

ExpressionsExpressionsLive DemoLive Demo

Page 41: 03. Operators, Expressions and Statements

SummarySummary

We discussed the operators in C#:We discussed the operators in C#: Arithmetic, logical, bitwise, Arithmetic, logical, bitwise,

comparison, assignment and otherscomparison, assignment and others Operator precedence Operator precedence

We learned when to use implicit We learned when to use implicit and explicit type conversionsand explicit type conversions

We learned how to use expressionsWe learned how to use expressions

41

Page 42: 03. Operators, Expressions and Statements

QuestionsQuestions??

Operators and Operators and ExpressionsExpressions

http://academy.telerik.com

Page 43: 03. Operators, Expressions and Statements

ExercisesExercises1.1. Write an expression that checks if given Write an expression that checks if given

integer is odd or even.integer is odd or even.

2.2. Write a boolean expression that checks for Write a boolean expression that checks for given integer if it can be divided (without given integer if it can be divided (without remainder) by 7 and 5 in the same time.remainder) by 7 and 5 in the same time.

3.3. Write an expression that calculates Write an expression that calculates rectangle’s area by given rectangle’s area by given widthwidth and and heightheight..

4.4. Write an expression that checks for given Write an expression that checks for given integer if its third digit (right-to-left) is integer if its third digit (right-to-left) is 77. E. . E. g. g. 17321732 truetrue..

5.5. Write a boolean expression for finding if Write a boolean expression for finding if the bit the bit 33 (counting from (counting from 00) of a given ) of a given integer is integer is 11 or or 00..

6.6. Write an expression that checks if given Write an expression that checks if given point (point (xx, , yy) is within a circle K() is within a circle K(OO, , 55).).

43

Page 44: 03. Operators, Expressions and Statements

Exercises (2)Exercises (2)

7.7. Write an expression that checks if given Write an expression that checks if given positive integer number positive integer number nn ( (nn ≤≤ 100) is prime. 100) is prime. E.g. E.g. 3737 is prime. is prime.

8.8. Write an expression that calculates trapezoid's Write an expression that calculates trapezoid's area by given sides area by given sides aa and and bb and height and height hh..

9.9. Write an expression that checks for given Write an expression that checks for given point (x, y) if it is within the circle K( (point (x, y) if it is within the circle K( (11,,11), ), 33) ) and out of the rectangle R(top=and out of the rectangle R(top=11, left=, left=-1-1, , width=width=66, height=, height=22).).

10.10. Write a boolean expression that returns if the Write a boolean expression that returns if the bit at position bit at position pp (counting from (counting from 00) in a given ) in a given integer number integer number vv has value of has value of 11. Example: . Example: vv==55; ; pp==11 false. false. 44

Page 45: 03. Operators, Expressions and Statements

Exercises (3)Exercises (3)

11.11. Write an expression that extracts from a Write an expression that extracts from a given integer given integer ii the value of a given bit the value of a given bit number number bb. Example: i=5; b=2 . Example: i=5; b=2 value=1. value=1.

12.12. We are given integer number We are given integer number nn, value , value vv ((vv=0 or 1) and a position =0 or 1) and a position pp. Write a . Write a sequence of operators that modifies sequence of operators that modifies nn to to hold the value hold the value vv at the position at the position pp from the from the binary representation of binary representation of nn..

Example: n = 5 (00000101), p=3, v=1 Example: n = 5 (00000101), p=3, v=1 13 13 (00001101)(00001101)

n = 5 (00000101), p=2, v=0 n = 5 (00000101), p=2, v=0 1 1 (00000001)(00000001) 45

Page 46: 03. Operators, Expressions and Statements

Exercises (4)Exercises (4)

13.13. Write a program that exchanges bits 3, Write a program that exchanges bits 3, 4 and 5 with bits 24,25 and 26 of given 4 and 5 with bits 24,25 and 26 of given 32-bit unsigned integer.32-bit unsigned integer.

14.14. * Write a program that exchanges bits * Write a program that exchanges bits {p, p+1, …, p+k-1) with bits {q, q+1, {p, p+1, …, p+k-1) with bits {q, q+1, q+k-1} of given 32-bit unsigned q+k-1} of given 32-bit unsigned integer.integer.

46