SlideShare a Scribd company logo
Operators and Expressions
Performing Simple Calculations with C#
Svetlin Nakov
Telerik Software Academy
academy.telerik.com
ManagerTechnical trainer
www.nakov.com
Table of Contents
1. Operators in C# and Operator Precedence
2. Arithmetic Operators
3. Logical Operators
4. Bitwise Operators
5. Comparison Operators
6. Assignment Operators
7. Other Operators
8. Implicit and ExplicitType Conversions
9. Expressions
2
Operators in C#
Arithmetic, Logical, Comparison, Assignment, Etc.
What is an Operator?
 Operator is an operation performed over data
at 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 and
operands that are evaluated to a single value
4
Operators in C#
 Operators in C# :
 Unary – take one operand
 Binary – take two operands
 Ternary (?:) – takes three operands
 Except for the assignment operators, all
binary operators are left-associative
 The assignment operators and the
conditional operator (?:) are right-associative
5
Categories of Operators in C#
Category Operators
Arithmetic + - * / % ++ --
Logical && || ^ !
Binary & | ^ ~ << >>
Comparison == != < > <= >=
Assignment
= += -= *= /= %= &= |=
^= <<= >>=
String concatenation +
Type conversion is as typeof
Other . [] () ?: new
6
Operators Precedence
Operators Precedence
Precedence Operators
Highest ()
++ -- (postfix) new typeof
++ -- (prefix) + - (unary) ! ~
* / %
+ -
<< >>
< > <= >= is as
== !=
&
Lower ^
8
Operators Precedence (2)
Precedence Operators
Higher |
&&
||
?:
Lowest
= *= /= %= += -= <<= >>= &= ^=
|=
9
 Parenthesis operator always has highest
precedence
 Note: prefer using parentheses, even when it
seems stupid to do so
Arithmetic Operators
Arithmetic Operators
 Arithmetic operators +, -, * are the same as in
math
 Division operator / if used on integers returns
integer (without rounding) or exception
 Division operator / if used on real numbers
returns real number or Infinity or NaN
 Remainder operator % returns the remainder
from division of integers
 The special addition operator ++ increments a
variable 11
Arithmetic Operators – Example
12
int squarePerimeter = 17;
double squareSide = squarePerimeter / 4.0;
double squareArea = squareSide * squareSide;
Console.WriteLine(squareSide); // 4.25
Console.WriteLine(squareArea); // 18.0625
int a = 5;
int b = 4;
Console.WriteLine( a + b ); // 9
Console.WriteLine( a + b++ ); // 9
Console.WriteLine( a + b ); // 10
Console.WriteLine( a + (++b) ); // 11
Console.WriteLine( a + b ); // 11
Console.WriteLine(12 / 3); // 4
Console.WriteLine(11 / 3); // 3
Arithmetic Operators –
Example (2)
13
Console.WriteLine(11.0 / 3); // 3.666666667
Console.WriteLine(11 / 3.0); // 3.666666667
Console.WriteLine(11 % 3); // 2
Console.WriteLine(11 % -3); // 2
Console.WriteLine(-11 % 3); // -2
Console.WriteLine(1.5 / 0.0); // Infinity
Console.WriteLine(-1.5 / 0.0); // -Infinity
Console.WriteLine(0.0 / 0.0); // NaN
int x = 0;
Console.WriteLine(5 / x); // DivideByZeroException
Arithmetic Operators –
Overflow Examples
14
int bigNum = 2000000000;
int bigSum = 2 * bigNum; // Integer overflow!
Console.WriteLine(bigSum); // -294967296
bigNum = Int32.MaxValue;
bigNum = bigNum + 1;
Console.WriteLine(bigNum); // -2147483648
checked
{
// This will cause OverflowException
bigSum = bigNum * 2;
}
Arithmetic Operators
Live Demo
Logical Operators
Logical Operators
 Logical operators take boolean operands and
return boolean result
 Operator ! turns true to false and false
to true
 Behavior of the operators &&, || and ^
(1 == true, 0 == false) :
17
Operation || || || || && && && && ^ ^ ^ ^
Operand1 0 0 1 1 0 0 1 1 0 0 1 1
Operand2 0 1 0 1 0 1 0 1 0 1 0 1
Result 0 1 1 1 0 0 0 1 0 1 1 0
Logical Operators – Example
 Using the logical operators:
18
bool a = true;
bool b = false;
Console.WriteLine(a && b); // False
Console.WriteLine(a || b); // True
Console.WriteLine(a ^ b); // True
Console.WriteLine(!b); // True
Console.WriteLine(b || true); // True
Console.WriteLine(b && true); // False
Console.WriteLine(a || true); // True
Console.WriteLine(a && true); // True
Console.WriteLine(!a); // False
Console.WriteLine((5>7) ^ (a==b)); // False
Logical Operators
Live Demo
Bitwise Operators
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 ^:
21
Operation | | | | & & & & ^ ^ ^ ^
Operand1 0 0 1 1 0 0 1 1 0 0 1 1
Operand2 0 1 0 1 0 1 0 1 0 1 0 1
Result 0 1 1 1 0 0 0 1 0 1 1 0
Bitwise Operators (2)
 Bitwise operators are used on integer numbers
(byte, sbyte, int, uint, long, ulong)
 Bitwise operators are applied bit by bit
 Examples:
22
ushort a = 3; // 00000000 00000011
ushort b = 5; // 00000000 00000101
Console.WriteLine( a | b); // 00000000 00000111
Console.WriteLine( a & b); // 00000000 00000001
Console.WriteLine( a ^ b); // 00000000 00000110
Console.WriteLine(~a & b); // 00000000 00000100
Console.WriteLine( a << 1); // 00000000 00000110
Console.WriteLine( a >> 1); // 00000000 00000001
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?
23
int p = 5;
int n = 35; // 00000000 00100011
int mask = 1 << p; // 00000000 00100000
int nAndMask = n & mask; // 00000000 00100000
int bit = nAndMask >> p; // 00000000 00000001
Console.WriteLine(bit); // 1
int p = 5;
int n = 35; // 00000000 00100011
int mask = ~(1 << p); // 11111111 11011111
int result = n & mask; // 00000000 00000011
Console.WriteLine(result); // 3
Bitwise Operators –
Tips &Tricks (2)
 How to set the bit at position p to 1?
 How to print a binary number to the console?
24
int p = 4;
int n = 35; // 00000000 00100011
int mask = 1 << p; // 00000000 00010000
int result = n | mask; // 00000000 00110011
Console.WriteLine(result); // 3
Console.WriteLine(
Convert.ToString(result, 2).PadLeft(32, '0'));
// 00000000000000000000000000110011
Bitwise Operators
Live Demo
Comparison and
Assignment Operators
Comparison Operators
 Comparison operators are used to compare
variables
 ==, <, >, >=, <=, !=
 Comparison operators example:
27
int a = 5;
int b = 4;
Console.WriteLine(a >= b); // True
Console.WriteLine(a != b); // True
Console.WriteLine(a == b); // False
Console.WriteLine(a == a); // True
Console.WriteLine(a != ++b); // False
Console.WriteLine(a > b); // False
Assignment Operators
 Assignment operators are used to assign a
value to a variable ,
 =, +=, -=, |=, ...
 Assignment operators example:
28
int x = 6;
int y = 4;
Console.WriteLine(y *= 2); // 8
int z = y = 3; // y=3 and z=3
Console.WriteLine(z); // 3
Console.WriteLine(x |= 1); // 7
Console.WriteLine(x += 3); // 10
Console.WriteLine(x /= 2); // 5
Comparison and
Assignment Operators
Live Demo
Other Operators
Other Operators
 String concatenation operator + is used to
concatenate strings
 If the second operand is not a string, it is
converted to string automatically
31
string first = "First";
string second = "Second";
Console.WriteLine(first + second);
// FirstSecond
string output = "The number is : ";
int number = 5;
Console.WriteLine(output + number);
// The number is : 5
Other Operators (2)
 Member access operator . is used to access
object members
 Square brackets [] are used with arrays
indexers and attributes
 Parentheses ( ) are used to override the
default operator precedence
 Class cast operator (type) is used to cast one
compatible type to another
32
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.Type
object (the reflection of a type)
 The is operator checks if an object is
compatible with given type
33
b ? x : y
Other Operators
 Null-coalescing operator ?? is used to define a
default value for both nullable value types and
reference types
 It returns the left-hand operand if it is not null
 Otherwise it returns the right operand
34
int? x = null;
int y = x ?? -1;
int? x = 1;
int y = x ?? -1;
Here the value of y is -1
Here the value of y is 1
Other Operators – Example
 Using some other operators:
35
int a = 6;
int b = 4;
Console.WriteLine(a > b ? "a>b" : "b>=a"); // a>b
Console.WriteLine((long) a); // 6
int c = b = 3; // b=3; followed by c=3;
Console.WriteLine(c); // 3
Console.WriteLine(a is int); // True
Console.WriteLine((a+b)/2); // 4
Console.WriteLine(typeof(int)); // System.Int32
int d = new int();
Console.WriteLine(d); // 0
Other Operators
Live Demo
Implicit and Explicit
Type Conversions
ImplicitType Conversion
 Implicit type conversion
 Automatic conversion of value of one data type
to value of another data type
 Allowed when no loss of data is possible
 "Larger" types can implicitly take values of
smaller "types"
 Example:
38
int i = 5;
long l = i;
ExplicitType Conversion
 Explicit type conversion
 Manual conversion of a value of one data type
to a value of another data type
 Allowed only explicitly by (type) operator
 Required when there is a possibility of loss of
data or precision
 Example:
39
long l = 5;
int i = (int) l;
Type Conversions – Example
 Example of implicit and explicit conversions:
 Note: Explicit conversion may be used even if
not required by the compiler
40
float heightInMeters = 1.74f; // Explicit conversion
double maxHeight = heightInMeters; // Implicit
double minHeight = (double) heightInMeters; // Explicit
float actualHeight = (float) maxHeight; // Explicit
float maxHeightFloat = maxHeight; // Compilation error!
Type Conversions
Live Demo
Expressions
Expressions
 Expressions are sequences of operators,
literals and variables that are evaluated to
some value
 Examples:
43
int r = (150-20) / 2 + 5; // r=70
// Expression for calculation of circle area
double surface = Math.PI * r * r;
// Expression for calculation of circle perimeter
double perimeter = 2 * Math.PI * r;
Expressions (2)
 Expressions has:
 Type (integer, real, boolean, ...)
 Value
 Examples:
44
int a = 2 + 3; // a = 5
int b = (a+3) * (a-4) + (2*a + 7) / 4; // b = 12
bool greater = (a > b) || ((a == 0) && (b == 0));
Expression of type
int. Calculated at
compile time.
Expression
of type int.
Calculated
at runtime.
Expression of type bool.
Calculated at runtime.
Expressions
Live Demo
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 explicit
type conversions
 We learned how to use expressions
46
Resources
 Boolean algebra (logic)
 http://en.wikipedia.org/wiki/Boolean_algebra_
%28logic%29
 Bitwise mask
 http://en.wikipedia.org/wiki/Mask_%28computi
ng%29
 Bitwise operation
 http://en.wikipedia.org/wiki/Bitwise_operation
 BitTwiddling Hacks
 graphics.stanford.edu/~seander/bithacks.html
47
форум програмиране,форум уеб дизайн
курсове и уроци по програмиране,уеб дизайн – безплатно
програмиранеза деца – безплатни курсове и уроци
безплатен SEO курс -оптимизация за търсачки
уроци по уеб дизайн, HTML,CSS, JavaScript,Photoshop
уроци по програмиранеи уеб дизайн за ученици
ASP.NET MVCкурс – HTML,SQL,C#,.NET,ASP.NETMVC
безплатен курс"Разработка на софтуер в cloud среда"
BG Coder -онлайн състезателна система -online judge
курсове и уроци по програмиране,книги – безплатно отНаков
безплатен курс"Качествен програменкод"
алго академия – състезателно програмиране,състезания
ASP.NET курс -уеб програмиране,бази данни, C#,.NET,ASP.NET
курсове и уроци по програмиране– Телерик академия
курсмобилни приложения с iPhone, Android,WP7,PhoneGap
freeC#book, безплатна книга C#,книга Java,книга C#
Дончо Минков -сайт за програмиране
Николай Костов -блог за програмиране
C#курс,програмиране,безплатно
Operators and Expressions
http://academy.telerik.com
Exercises
1. Write an expression that checks if given integer is
odd or even.
2. Write a boolean expression that checks for given
integer if it can be divided (without remainder) by 7
and 5 in the same time.
3. Write an expression that calculates rectangle’s area
by given width and height.
4. Write an expression that checks for given integer if
its third digit (right-to-left) is 7. E. g. 1732  true.
5. Write a boolean expression for finding if the bit 3
(counting from 0) of a given integer is 1 or 0.
6. Write an expression that checks if given point (x, y)
is within a circle K(O, 5). 49
Exercises (2)
7. Write an expression that checks if given positive
integer number n (n ≤ 100) is prime. E.g. 37 is prime.
8. Write an expression that calculates trapezoid's area
by given sides a and b and height h.
9. Write an expression that checks for given point (x, y)
if it is within the circle K( (1,1), 3) and out of the
rectangle R(top=1, left=-1, width=6, height=2).
10. Write a boolean expression that returns if the bit at
position p (counting from 0) in a given integer
number v has value of 1. Example: v=5; p=1  false.
50
Exercises (3)
11. Write an expression that extracts from a given
integer i the value of a given bit number b.
Example: i=5; b=2  value=1.
12. We are given integer number n, value v (v=0 or 1)
and a position p.Write a sequence of operators that
modifies n to hold the value v at the position p from
the binary representation of n.
Example: n = 5 (00000101), p=3, v=1  13 (00001101)
n = 5 (00000101), p=2, v=0  1 (00000001)
51
Exercises (4)
13. Write a program that exchanges bits 3, 4 and 5 with
bits 24, 25 and 26 of given 32-bit unsigned integer.
14. *Write a program that exchanges bits {p, p+1, …,
p+k-1) with bits {q, q+1, …, q+k-1} of given 32-bit
unsigned integer.
52
FreeTrainings @Telerik Academy
 Fundamentals of C# Programming
Course
 csharpfundamentals.telerik.com
 Telerik Software Academy
 academy.telerik.com
 Telerik Academy @ Facebook
 facebook.com/TelerikAcademy
 Telerik Software Academy Forums
 forums.academy.telerik.com

More Related Content

What's hot

Basic c operators
Basic c operatorsBasic c operators
Basic c operators
Anuja Lad
 
Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++
Himanshu Kaushik
 
Python : basic operators
Python : basic operatorsPython : basic operators
Python : basic operators
S.M. Salaquzzaman
 
Operators in C/C++
Operators in C/C++Operators in C/C++
Operators in C/C++
Shobi P P
 
Python Basic Operators
Python Basic OperatorsPython Basic Operators
Python Basic Operators
Soba Arjun
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
bajiajugal
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
sanya6900
 
Operators in python
Operators in pythonOperators in python
Operators in python
deepalishinkar1
 
Operators
OperatorsOperators
Operators
Kamran
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++
Online
 
Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssions
eShikshak
 
Few Operator used in c++
Few Operator used in c++Few Operator used in c++
Few Operator used in c++
sunny khan
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
temkin abdlkader
 
Operators in python
Operators in pythonOperators in python
Operators in python
Prabhakaran V M
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
Neeru Mittal
 
C ppt
C pptC ppt
C ppt
jasmeen kr
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
Anusuya123
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 

What's hot (18)

Basic c operators
Basic c operatorsBasic c operators
Basic c operators
 
Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++
 
Python : basic operators
Python : basic operatorsPython : basic operators
Python : basic operators
 
Operators in C/C++
Operators in C/C++Operators in C/C++
Operators in C/C++
 
Python Basic Operators
Python Basic OperatorsPython Basic Operators
Python Basic Operators
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Operators
OperatorsOperators
Operators
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++
 
Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssions
 
Few Operator used in c++
Few Operator used in c++Few Operator used in c++
Few Operator used in c++
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
C ppt
C pptC ppt
C ppt
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 

Similar to 3 operators-expressions-and-statements-120712073351-phpapp01

03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statements
Intro C# Book
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
Fiaz Khokhar
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
Raghu nath
 
Report on c
Report on cReport on c
Report on c
jasmeen kr
 
ppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operatorsppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operators
Amrinder Sidhu
 
Operators in C++.pptx
Operators in C++.pptxOperators in C++.pptx
Operators in C++.pptx
ssuser41748c
 
Operators in Python Arithmetic Operators
Operators in Python Arithmetic OperatorsOperators in Python Arithmetic Operators
Operators in Python Arithmetic Operators
ramireddyobulakondar
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
Operators
OperatorsOperators
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
Rohit Shrivastava
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
Rohit Shrivastava
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
jahanullah
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
guest58c84c
 
Operators
OperatorsOperators
Operators
VijayaLakshmi506
 
ICP - Lecture 5
ICP - Lecture 5ICP - Lecture 5
ICP - Lecture 5
Hassaan Rahman
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Operators_in_Python_Simplified_languages
Operators_in_Python_Simplified_languagesOperators_in_Python_Simplified_languages
Operators_in_Python_Simplified_languages
AbhishekGupta692777
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
Soran University
 
Theory3
Theory3Theory3

Similar to 3 operators-expressions-and-statements-120712073351-phpapp01 (20)

03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statements
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
 
Report on c
Report on cReport on c
Report on c
 
ppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operatorsppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operators
 
Operators in C++.pptx
Operators in C++.pptxOperators in C++.pptx
Operators in C++.pptx
 
Operators in Python Arithmetic Operators
Operators in Python Arithmetic OperatorsOperators in Python Arithmetic Operators
Operators in Python Arithmetic Operators
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Operators
OperatorsOperators
Operators
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
Operators
OperatorsOperators
Operators
 
ICP - Lecture 5
ICP - Lecture 5ICP - Lecture 5
ICP - Lecture 5
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Operators_in_Python_Simplified_languages
Operators_in_Python_Simplified_languagesOperators_in_Python_Simplified_languages
Operators_in_Python_Simplified_languages
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Theory3
Theory3Theory3
Theory3
 

More from Abdul Samee

3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
Abdul Samee
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 
Input outputdisplaydevices-140819061228-phpapp02
Input outputdisplaydevices-140819061228-phpapp02Input outputdisplaydevices-140819061228-phpapp02
Input outputdisplaydevices-140819061228-phpapp02
Abdul Samee
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
Abdul Samee
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 

More from Abdul Samee (6)

3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
Input outputdisplaydevices-140819061228-phpapp02
Input outputdisplaydevices-140819061228-phpapp02Input outputdisplaydevices-140819061228-phpapp02
Input outputdisplaydevices-140819061228-phpapp02
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 

3 operators-expressions-and-statements-120712073351-phpapp01

  • 1. Operators and Expressions Performing Simple Calculations with C# Svetlin Nakov Telerik Software Academy academy.telerik.com ManagerTechnical trainer www.nakov.com
  • 2. Table of Contents 1. Operators in C# and Operator Precedence 2. Arithmetic Operators 3. Logical Operators 4. Bitwise Operators 5. Comparison Operators 6. Assignment Operators 7. Other Operators 8. Implicit and ExplicitType Conversions 9. Expressions 2
  • 3. Operators in C# Arithmetic, Logical, Comparison, Assignment, Etc.
  • 4. What is an Operator?  Operator is an operation performed over data at 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 and operands that are evaluated to a single value 4
  • 5. Operators in C#  Operators in C# :  Unary – take one operand  Binary – take two operands  Ternary (?:) – takes three operands  Except for the assignment operators, all binary operators are left-associative  The assignment operators and the conditional operator (?:) are right-associative 5
  • 6. Categories of Operators in C# Category Operators Arithmetic + - * / % ++ -- Logical && || ^ ! Binary & | ^ ~ << >> Comparison == != < > <= >= Assignment = += -= *= /= %= &= |= ^= <<= >>= String concatenation + Type conversion is as typeof Other . [] () ?: new 6
  • 8. Operators Precedence Precedence Operators Highest () ++ -- (postfix) new typeof ++ -- (prefix) + - (unary) ! ~ * / % + - << >> < > <= >= is as == != & Lower ^ 8
  • 9. Operators Precedence (2) Precedence Operators Higher | && || ?: Lowest = *= /= %= += -= <<= >>= &= ^= |= 9  Parenthesis operator always has highest precedence  Note: prefer using parentheses, even when it seems stupid to do so
  • 11. Arithmetic Operators  Arithmetic operators +, -, * are the same as in math  Division operator / if used on integers returns integer (without rounding) or exception  Division operator / if used on real numbers returns real number or Infinity or NaN  Remainder operator % returns the remainder from division of integers  The special addition operator ++ increments a variable 11
  • 12. Arithmetic Operators – Example 12 int squarePerimeter = 17; double squareSide = squarePerimeter / 4.0; double squareArea = squareSide * squareSide; Console.WriteLine(squareSide); // 4.25 Console.WriteLine(squareArea); // 18.0625 int a = 5; int b = 4; Console.WriteLine( a + b ); // 9 Console.WriteLine( a + b++ ); // 9 Console.WriteLine( a + b ); // 10 Console.WriteLine( a + (++b) ); // 11 Console.WriteLine( a + b ); // 11 Console.WriteLine(12 / 3); // 4 Console.WriteLine(11 / 3); // 3
  • 13. Arithmetic Operators – Example (2) 13 Console.WriteLine(11.0 / 3); // 3.666666667 Console.WriteLine(11 / 3.0); // 3.666666667 Console.WriteLine(11 % 3); // 2 Console.WriteLine(11 % -3); // 2 Console.WriteLine(-11 % 3); // -2 Console.WriteLine(1.5 / 0.0); // Infinity Console.WriteLine(-1.5 / 0.0); // -Infinity Console.WriteLine(0.0 / 0.0); // NaN int x = 0; Console.WriteLine(5 / x); // DivideByZeroException
  • 14. Arithmetic Operators – Overflow Examples 14 int bigNum = 2000000000; int bigSum = 2 * bigNum; // Integer overflow! Console.WriteLine(bigSum); // -294967296 bigNum = Int32.MaxValue; bigNum = bigNum + 1; Console.WriteLine(bigNum); // -2147483648 checked { // This will cause OverflowException bigSum = bigNum * 2; }
  • 17. Logical Operators  Logical operators take boolean operands and return boolean result  Operator ! turns true to false and false to true  Behavior of the operators &&, || and ^ (1 == true, 0 == false) : 17 Operation || || || || && && && && ^ ^ ^ ^ Operand1 0 0 1 1 0 0 1 1 0 0 1 1 Operand2 0 1 0 1 0 1 0 1 0 1 0 1 Result 0 1 1 1 0 0 0 1 0 1 1 0
  • 18. Logical Operators – Example  Using the logical operators: 18 bool a = true; bool b = false; Console.WriteLine(a && b); // False Console.WriteLine(a || b); // True Console.WriteLine(a ^ b); // True Console.WriteLine(!b); // True Console.WriteLine(b || true); // True Console.WriteLine(b && true); // False Console.WriteLine(a || true); // True Console.WriteLine(a && true); // True Console.WriteLine(!a); // False Console.WriteLine((5>7) ^ (a==b)); // False
  • 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 ^: 21 Operation | | | | & & & & ^ ^ ^ ^ Operand1 0 0 1 1 0 0 1 1 0 0 1 1 Operand2 0 1 0 1 0 1 0 1 0 1 0 1 Result 0 1 1 1 0 0 0 1 0 1 1 0
  • 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: 22 ushort a = 3; // 00000000 00000011 ushort b = 5; // 00000000 00000101 Console.WriteLine( a | b); // 00000000 00000111 Console.WriteLine( a & b); // 00000000 00000001 Console.WriteLine( a ^ b); // 00000000 00000110 Console.WriteLine(~a & b); // 00000000 00000100 Console.WriteLine( a << 1); // 00000000 00000110 Console.WriteLine( a >> 1); // 00000000 00000001
  • 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? 23 int p = 5; int n = 35; // 00000000 00100011 int mask = 1 << p; // 00000000 00100000 int nAndMask = n & mask; // 00000000 00100000 int bit = nAndMask >> p; // 00000000 00000001 Console.WriteLine(bit); // 1 int p = 5; int n = 35; // 00000000 00100011 int mask = ~(1 << p); // 11111111 11011111 int result = n & mask; // 00000000 00000011 Console.WriteLine(result); // 3
  • 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? 24 int p = 4; int n = 35; // 00000000 00100011 int mask = 1 << p; // 00000000 00010000 int result = n | mask; // 00000000 00110011 Console.WriteLine(result); // 3 Console.WriteLine( Convert.ToString(result, 2).PadLeft(32, '0')); // 00000000000000000000000000110011
  • 27. Comparison Operators  Comparison operators are used to compare variables  ==, <, >, >=, <=, !=  Comparison operators example: 27 int a = 5; int b = 4; Console.WriteLine(a >= b); // True Console.WriteLine(a != b); // True Console.WriteLine(a == b); // False Console.WriteLine(a == a); // True Console.WriteLine(a != ++b); // False Console.WriteLine(a > b); // False
  • 28. Assignment Operators  Assignment operators are used to assign a value to a variable ,  =, +=, -=, |=, ...  Assignment operators example: 28 int x = 6; int y = 4; Console.WriteLine(y *= 2); // 8 int z = y = 3; // y=3 and z=3 Console.WriteLine(z); // 3 Console.WriteLine(x |= 1); // 7 Console.WriteLine(x += 3); // 10 Console.WriteLine(x /= 2); // 5
  • 31. Other Operators  String concatenation operator + is used to concatenate strings  If the second operand is not a string, it is converted to string automatically 31 string first = "First"; string second = "Second"; Console.WriteLine(first + second); // FirstSecond string output = "The number is : "; int number = 5; Console.WriteLine(output + number); // The number is : 5
  • 32. Other Operators (2)  Member access operator . is used to access object members  Square brackets [] are used with arrays indexers and attributes  Parentheses ( ) are used to override the default operator precedence  Class cast operator (type) is used to cast one compatible type to another 32
  • 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.Type object (the reflection of a type)  The is operator checks if an object is compatible with given type 33 b ? x : y
  • 34. Other Operators  Null-coalescing operator ?? is used to define a default value for both nullable value types and reference types  It returns the left-hand operand if it is not null  Otherwise it returns the right operand 34 int? x = null; int y = x ?? -1; int? x = 1; int y = x ?? -1; Here the value of y is -1 Here the value of y is 1
  • 35. Other Operators – Example  Using some other operators: 35 int a = 6; int b = 4; Console.WriteLine(a > b ? "a>b" : "b>=a"); // a>b Console.WriteLine((long) a); // 6 int c = b = 3; // b=3; followed by c=3; Console.WriteLine(c); // 3 Console.WriteLine(a is int); // True Console.WriteLine((a+b)/2); // 4 Console.WriteLine(typeof(int)); // System.Int32 int d = new int(); Console.WriteLine(d); // 0
  • 38. ImplicitType Conversion  Implicit type conversion  Automatic conversion of value of one data type to value of another data type  Allowed when no loss of data is possible  "Larger" types can implicitly take values of smaller "types"  Example: 38 int i = 5; long l = i;
  • 39. ExplicitType Conversion  Explicit type conversion  Manual conversion of a value of one data type to a value of another data type  Allowed only explicitly by (type) operator  Required when there is a possibility of loss of data or precision  Example: 39 long l = 5; int i = (int) l;
  • 40. Type Conversions – Example  Example of implicit and explicit conversions:  Note: Explicit conversion may be used even if not required by the compiler 40 float heightInMeters = 1.74f; // Explicit conversion double maxHeight = heightInMeters; // Implicit double minHeight = (double) heightInMeters; // Explicit float actualHeight = (float) maxHeight; // Explicit float maxHeightFloat = maxHeight; // Compilation error!
  • 43. Expressions  Expressions are sequences of operators, literals and variables that are evaluated to some value  Examples: 43 int r = (150-20) / 2 + 5; // r=70 // Expression for calculation of circle area double surface = Math.PI * r * r; // Expression for calculation of circle perimeter double perimeter = 2 * Math.PI * r;
  • 44. Expressions (2)  Expressions has:  Type (integer, real, boolean, ...)  Value  Examples: 44 int a = 2 + 3; // a = 5 int b = (a+3) * (a-4) + (2*a + 7) / 4; // b = 12 bool greater = (a > b) || ((a == 0) && (b == 0)); Expression of type int. Calculated at compile time. Expression of type int. Calculated at runtime. Expression of type bool. Calculated at runtime.
  • 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 explicit type conversions  We learned how to use expressions 46
  • 47. Resources  Boolean algebra (logic)  http://en.wikipedia.org/wiki/Boolean_algebra_ %28logic%29  Bitwise mask  http://en.wikipedia.org/wiki/Mask_%28computi ng%29  Bitwise operation  http://en.wikipedia.org/wiki/Bitwise_operation  BitTwiddling Hacks  graphics.stanford.edu/~seander/bithacks.html 47
  • 48. форум програмиране,форум уеб дизайн курсове и уроци по програмиране,уеб дизайн – безплатно програмиранеза деца – безплатни курсове и уроци безплатен SEO курс -оптимизация за търсачки уроци по уеб дизайн, HTML,CSS, JavaScript,Photoshop уроци по програмиранеи уеб дизайн за ученици ASP.NET MVCкурс – HTML,SQL,C#,.NET,ASP.NETMVC безплатен курс"Разработка на софтуер в cloud среда" BG Coder -онлайн състезателна система -online judge курсове и уроци по програмиране,книги – безплатно отНаков безплатен курс"Качествен програменкод" алго академия – състезателно програмиране,състезания ASP.NET курс -уеб програмиране,бази данни, C#,.NET,ASP.NET курсове и уроци по програмиране– Телерик академия курсмобилни приложения с iPhone, Android,WP7,PhoneGap freeC#book, безплатна книга C#,книга Java,книга C# Дончо Минков -сайт за програмиране Николай Костов -блог за програмиране C#курс,програмиране,безплатно Operators and Expressions http://academy.telerik.com
  • 49. Exercises 1. Write an expression that checks if given integer is odd or even. 2. Write a boolean expression that checks for given integer if it can be divided (without remainder) by 7 and 5 in the same time. 3. Write an expression that calculates rectangle’s area by given width and height. 4. Write an expression that checks for given integer if its third digit (right-to-left) is 7. E. g. 1732  true. 5. Write a boolean expression for finding if the bit 3 (counting from 0) of a given integer is 1 or 0. 6. Write an expression that checks if given point (x, y) is within a circle K(O, 5). 49
  • 50. Exercises (2) 7. Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime. 8. Write an expression that calculates trapezoid's area by given sides a and b and height h. 9. Write an expression that checks for given point (x, y) if it is within the circle K( (1,1), 3) and out of the rectangle R(top=1, left=-1, width=6, height=2). 10. Write a boolean expression that returns if the bit at position p (counting from 0) in a given integer number v has value of 1. Example: v=5; p=1  false. 50
  • 51. Exercises (3) 11. Write an expression that extracts from a given integer i the value of a given bit number b. Example: i=5; b=2  value=1. 12. We are given integer number n, value v (v=0 or 1) and a position p.Write a sequence of operators that modifies n to hold the value v at the position p from the binary representation of n. Example: n = 5 (00000101), p=3, v=1  13 (00001101) n = 5 (00000101), p=2, v=0  1 (00000001) 51
  • 52. Exercises (4) 13. Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer. 14. *Write a program that exchanges bits {p, p+1, …, p+k-1) with bits {q, q+1, …, q+k-1} of given 32-bit unsigned integer. 52
  • 53. FreeTrainings @Telerik Academy  Fundamentals of C# Programming Course  csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com  Telerik Academy @ Facebook  facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com

Editor's Notes

  1. 07/16/96
  2. 07/16/96
  3. 07/16/96
  4. 07/16/96
  5. 07/16/96
  6. 07/16/96
  7. 07/16/96
  8. 07/16/96
  9. 07/16/96
  10. 07/16/96
  11. 07/16/96
  12. 07/16/96
  13. 07/16/96
  14. 07/16/96
  15. 07/16/96
  16. 07/16/96
  17. 07/16/96
  18. 07/16/96
  19. 07/16/96
  20. 07/16/96
  21. 07/16/96
  22. 07/16/96