SlideShare a Scribd company logo
Operators and Expressions
Performing Simple Calculations with C#
Svetlin Nakov
Telerik Corporation
www.telerik.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#
6
Category Operators
Arithmetic + - * / % ++ --
Logical && || ^ !
Binary & | ^ ~ << >>
Comparison == != < > <= >=
Assignment
= += -= *= /= %= &= |=
^= <<= >>=
String concatenation +
Type conversion is as typeof
Other . [] () ?: new
Operators Precedence
Operators Precedence
8
Precedence Operators
Highest ++ -- (postfix) new typeof
++ -- (prefix) + - (unary) ! ~
* / %
+ -
<< >>
< > <= >= is as
== !=
&
Lower ^
Operators Precedence (2)
9
Precedence Operators
Higher |
&&
||
?:
Lowest
= *= /= %= += -= <<= >>= &=
^= |=
 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
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(11 / 3); // 3
Console.WriteLine(11 % 3); // 2
Console.WriteLine(12 / 3); // 4
12
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) :
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
15
Logical Operators – Example
 Using the logical operators:
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
16
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 ^:
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
19
Bitwise Operators (2)
 Bitwise operators are used on integer numbers
(byte, sbyte, int, uint, long, ulong)
 Bitwise operators are applied bit by bit
 Examples:
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
20
Bitwise Operators
Live Demo
Comparison and
Assignment Operators
Comparison Operators
 Comparison operators are used to compare
variables
 ==, <, >, >=, <=, !=
 Comparison operators example:
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
23
Assignment Operators
 Assignment operators are used to assign a
value to a variable ,
 =, +=, -=, |=, ...
 Assignment operators example:
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
24
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
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
27
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
28
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
b ? x : y
29
Other Operators – Example
 Using some other operators:
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
30
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:
int i = 5;
long l = i;
33
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:
long l = 5;
int i = (int) l;
34
Type Conversions – Example
 Example of implicit and explicit conversions:
 Note: Explicit conversion may be used even if
not required by the compiler
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!
35
Type Conversions
Live Demo
Expressions
Expressions
 Expressions are sequences of operators,
literals and variables that are evaluated to
some value
 Examples:
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;
38
Expressions (2)
 Expressions has:
 Type (integer, real, boolean, ...)
 Value
 Examples:
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.
39
Expressions
Live Demo
Summary
 We discussed the operators in C#:
 Arithmetic, logical, bitwise, comparison,
assignment and others
 Operator precedence
 We learned when to use implicit and explicit
type conversions
 We learned how to use expressions
41
Questions?
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).
43
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.
44
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)
45
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.
46

More Related Content

What's hot (20)

PPTX
Python Programming | JNTUK | UNIT 1 | Lecture 5
FabMinds
 
PPT
C Prog. - Operators and Expressions
vinay arora
 
PPTX
Operators in Python
Anusuya123
 
PPT
CBSE Class XI :- Operators in C++
Pranav Ghildiyal
 
PPT
Operators and Expressions in C++
Praveen M Jigajinni
 
PPTX
Operators and expressions
vishaljot_kaur
 
PPT
Frequently asked questions in c
David Livingston J
 
PPT
Chap 4 c++
Venkateswarlu Vuggam
 
PPT
Operation and expression in c++
Online
 
PPTX
Python Operators
Adheetha O. V
 
PPT
Operators in C++
Sachin Sharma
 
PPT
Frequently asked questions in c
David Livingston J
 
PDF
Assignment8
Sunita Milind Dol
 
ODP
operators in c++
Kartik Fulara
 
PPTX
Chapter 3 : Programming with Java Operators and Strings
It Academy
 
DOCX
Basics of c++
Gunjan Mathur
 
PPT
Basic concept of c++
shashikant pabari
 
PPTX
Python operators
SaurabhUpadhyay73
 
PPTX
Ch7 Basic Types
SzeChingChen
 
PPTX
Python Training in Bangalore | Python Operators | Learnbay.in
Learnbayin
 
Python Programming | JNTUK | UNIT 1 | Lecture 5
FabMinds
 
C Prog. - Operators and Expressions
vinay arora
 
Operators in Python
Anusuya123
 
CBSE Class XI :- Operators in C++
Pranav Ghildiyal
 
Operators and Expressions in C++
Praveen M Jigajinni
 
Operators and expressions
vishaljot_kaur
 
Frequently asked questions in c
David Livingston J
 
Operation and expression in c++
Online
 
Python Operators
Adheetha O. V
 
Operators in C++
Sachin Sharma
 
Frequently asked questions in c
David Livingston J
 
Assignment8
Sunita Milind Dol
 
operators in c++
Kartik Fulara
 
Chapter 3 : Programming with Java Operators and Strings
It Academy
 
Basics of c++
Gunjan Mathur
 
Basic concept of c++
shashikant pabari
 
Python operators
SaurabhUpadhyay73
 
Ch7 Basic Types
SzeChingChen
 
Python Training in Bangalore | Python Operators | Learnbay.in
Learnbayin
 

Viewers also liked (7)

PPT
05 Conditional statements
maznabili
 
PPT
15 Text files
maznabili
 
PPT
19 Algorithms and complexity
maznabili
 
PPT
01 Introduction to programming
maznabili
 
PPT
For Beginners - C#
Snehal Harawande
 
PPTX
C# overview part 1
sagaroceanic11
 
PDF
Responding to Academically Distressed Students
Mr. Ronald Quileste, PhD
 
05 Conditional statements
maznabili
 
15 Text files
maznabili
 
19 Algorithms and complexity
maznabili
 
01 Introduction to programming
maznabili
 
For Beginners - C#
Snehal Harawande
 
C# overview part 1
sagaroceanic11
 
Responding to Academically Distressed Students
Mr. Ronald Quileste, PhD
 
Ad

Similar to 03 Operators and expressions (20)

PPTX
3 operators-expressions-and-statements-120712073351-phpapp01
Abdul Samee
 
PPTX
3 operators-expressions-and-statements-120712073351-phpapp01
Abdul Samee
 
PPTX
03. Operators Expressions and statements
Intro C# Book
 
PPTX
Operators expressions-and-statements
CtOlaf
 
PPT
Operators
Kamran
 
PPT
Lecture 2
Soran University
 
PPT
Operators and Expressions in C#
Prasanna Kumar SM
 
PPT
C Sharp Jn (2)
guest58c84c
 
PPT
C Sharp Jn (2)
jahanullah
 
PPTX
11operator in c#
Sireesh K
 
PPS
02 iec t1_s1_oo_ps_session_02
Pooja Gupta
 
ODP
Operators
jayesh30sikchi
 
PPTX
2.overview of c#
Raghu nath
 
PPT
4_A1208223655_21789_2_2018_04. Operators.ppt
RithwikRanjan
 
PDF
C sharp chap3
Mukesh Tekwani
 
PDF
Learn C# Programming - Operators
Eng Teong Cheah
 
PPTX
C sharp part 001
Ralph Weber
 
PPTX
Operators and expression in c#
Dr.Neeraj Kumar Pandey
 
PPTX
C# 101: Intro to Programming with C#
Hawkman Academy
 
PPT
JavaScript Operators
Charles Russell
 
3 operators-expressions-and-statements-120712073351-phpapp01
Abdul Samee
 
3 operators-expressions-and-statements-120712073351-phpapp01
Abdul Samee
 
03. Operators Expressions and statements
Intro C# Book
 
Operators expressions-and-statements
CtOlaf
 
Operators
Kamran
 
Lecture 2
Soran University
 
Operators and Expressions in C#
Prasanna Kumar SM
 
C Sharp Jn (2)
guest58c84c
 
C Sharp Jn (2)
jahanullah
 
11operator in c#
Sireesh K
 
02 iec t1_s1_oo_ps_session_02
Pooja Gupta
 
Operators
jayesh30sikchi
 
2.overview of c#
Raghu nath
 
4_A1208223655_21789_2_2018_04. Operators.ppt
RithwikRanjan
 
C sharp chap3
Mukesh Tekwani
 
Learn C# Programming - Operators
Eng Teong Cheah
 
C sharp part 001
Ralph Weber
 
Operators and expression in c#
Dr.Neeraj Kumar Pandey
 
C# 101: Intro to Programming with C#
Hawkman Academy
 
JavaScript Operators
Charles Russell
 
Ad

More from maznabili (19)

PPT
22 Methodology of problem solving
maznabili
 
PPT
21 High-quality programming code construction part-ii
maznabili
 
PPT
21 high-quality programming code construction part-i
maznabili
 
PPT
20 Object-oriented programming principles
maznabili
 
PPT
18 Hash tables and sets
maznabili
 
PPT
17 Trees and graphs
maznabili
 
PPT
16 Linear data structures
maznabili
 
PPT
14 Defining classes
maznabili
 
PPT
13 Strings and text processing
maznabili
 
PPT
12 Exceptions handling
maznabili
 
PPT
11 Using classes and objects
maznabili
 
PPT
10 Recursion
maznabili
 
PPT
09 Methods
maznabili
 
PPT
08 Numeral systems
maznabili
 
PPT
07 Arrays
maznabili
 
PPT
06 Loops
maznabili
 
PPT
04 Console input output-
maznabili
 
PPT
02 Primitive data types and variables
maznabili
 
PPT
00 Fundamentals of csharp course introduction
maznabili
 
22 Methodology of problem solving
maznabili
 
21 High-quality programming code construction part-ii
maznabili
 
21 high-quality programming code construction part-i
maznabili
 
20 Object-oriented programming principles
maznabili
 
18 Hash tables and sets
maznabili
 
17 Trees and graphs
maznabili
 
16 Linear data structures
maznabili
 
14 Defining classes
maznabili
 
13 Strings and text processing
maznabili
 
12 Exceptions handling
maznabili
 
11 Using classes and objects
maznabili
 
10 Recursion
maznabili
 
09 Methods
maznabili
 
08 Numeral systems
maznabili
 
07 Arrays
maznabili
 
06 Loops
maznabili
 
04 Console input output-
maznabili
 
02 Primitive data types and variables
maznabili
 
00 Fundamentals of csharp course introduction
maznabili
 

Recently uploaded (20)

PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
DOCX
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PDF
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
PPTX
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PDF
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
PPTX
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Practical Applications of AI in Local Government
OnBoard
 
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 

03 Operators and expressions

  • 1. Operators and Expressions Performing Simple Calculations with C# Svetlin Nakov Telerik Corporation www.telerik.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# 6 Category Operators Arithmetic + - * / % ++ -- Logical && || ^ ! Binary & | ^ ~ << >> Comparison == != < > <= >= Assignment = += -= *= /= %= &= |= ^= <<= >>= String concatenation + Type conversion is as typeof Other . [] () ?: new
  • 8. Operators Precedence 8 Precedence Operators Highest ++ -- (postfix) new typeof ++ -- (prefix) + - (unary) ! ~ * / % + - << >> < > <= >= is as == != & Lower ^
  • 9. Operators Precedence (2) 9 Precedence Operators Higher | && || ?: Lowest = *= /= %= += -= <<= >>= &= ^= |=  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 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(11 / 3); // 3 Console.WriteLine(11 % 3); // 2 Console.WriteLine(12 / 3); // 4 12
  • 15. 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) : 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 15
  • 16. Logical Operators – Example  Using the logical operators: 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 16
  • 19. 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 ^: 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 19
  • 20. Bitwise Operators (2)  Bitwise operators are used on integer numbers (byte, sbyte, int, uint, long, ulong)  Bitwise operators are applied bit by bit  Examples: 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 20
  • 23. Comparison Operators  Comparison operators are used to compare variables  ==, <, >, >=, <=, !=  Comparison operators example: 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 23
  • 24. Assignment Operators  Assignment operators are used to assign a value to a variable ,  =, +=, -=, |=, ...  Assignment operators example: 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 24
  • 27. Other Operators  String concatenation operator + is used to concatenate strings  If the second operand is not a string, it is converted to string automatically 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 27
  • 28. 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 28
  • 29. 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 b ? x : y 29
  • 30. Other Operators – Example  Using some other operators: 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 30
  • 33. 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: int i = 5; long l = i; 33
  • 34. 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: long l = 5; int i = (int) l; 34
  • 35. Type Conversions – Example  Example of implicit and explicit conversions:  Note: Explicit conversion may be used even if not required by the compiler 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! 35
  • 38. Expressions  Expressions are sequences of operators, literals and variables that are evaluated to some value  Examples: 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; 38
  • 39. Expressions (2)  Expressions has:  Type (integer, real, boolean, ...)  Value  Examples: 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. 39
  • 41. Summary  We discussed the operators in C#:  Arithmetic, logical, bitwise, comparison, assignment and others  Operator precedence  We learned when to use implicit and explicit type conversions  We learned how to use expressions 41
  • 43. 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). 43
  • 44. 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. 44
  • 45. 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) 45
  • 46. 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. 46

Editor's Notes