Performing Simple Calculations with C# Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
All the Operators. Precedence An operator with higher precedence is done earlier (prededes) one with lower precedence –A higher precedence is indicated.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
More about Numerical Computation CS-2301, B-Term More about Numerical Computation CS-2301, System Programming for Non-Majors (Slides include materials.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Expressions, Evaluation and Assignments
Performing Simple Calculations with C# Svetlin Nakov Telerik Corporation
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
Expressions & Assignments One of the original intentions of computer programs was the evaluation of mathematical expressions –languages would inherit much.
Data Types, Operators, Expressions, Statements, Console I/O, Loops, Arrays, Methods Svetlin Nakov Telerik Corporation
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 2 part #4 Operator
Object-Oriented Programming Using C++ Third Edition Chapter 2 Evaluating C++ Expressions.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Simple Data Types and Statements. Namespaces namespace MyNamespace { // …. { MyNamespace::func1() using namespace OtherNamespace; Comments: // /* xxxx.
CHAPTER 2 PART #4 OPERATOR 2 nd semester King Saud University College of Applied studies and Community Service Csc 1101 By: Asma Alosaimi Edited.
C# Language Overview (Part I)
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 3A Integral Data (Concepts)
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Data Types, Operators, Expressions, Statements, Console I/O, Loops, Arrays, Methods Svetlin Nakov Telerik Corporation
Chapter 2: Using Data.
Basic Operators. What is an operator? using expression is equal to 9. Here, 4 and 5 are called operands and + is the operator Python language supports.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
STATEMENTS AND FLOW OF EXECUTION CHAPTER 11 OF APRESS A PROGRAMMERS GUIDE TO C SHARP 5.0.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA TYPES AND OPERATIONS.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Perform Calculations and Control Flow Telerik Software Academy Learning & Development Team.
1 Operations Making Things Happen (Chap. 3) Expressions.
15-Nov-15 All the Operators. operators.ppt 2 Precedence An operator with higher precedence is done earlier (precedes) one with lower precedence A higher.
C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0.
COMP Primitive and Class Types Yi Hong May 14, 2015.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
COM S 207 Literal, Operator, and Expression Instructor: Ying Cai Department of Computer Science Iowa State University
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Chapter Two Operators and Expressions Lesson Seven.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1.2 Primitive Data Types and Variables
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Operators and Expressions
Programming Principles Operators and Expressions.
Chapter 7: Expressions and Assignment Statements
University of Central Florida COP 3330 Object Oriented Programming
Numeral Types and Type Conversion
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE
University of Central Florida COP 3330 Object Oriented Programming
Chapter 7: Expressions and Assignment Statements
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Computing with C# and the .NET Framework
Type Conversion, Constants, and the String Object
Operators and Expressions
Arithmetic Operator Operation Example + addition x + y
Arithmetic operations, decisions and looping
C Operators, Operands, Expressions & Statements
Chapter-3 Operators.
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Data Types and Expressions
Objectives Define and describe statements and expressions
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
Operator King Saud University
Problem 1 Given n, calculate 2n
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

Performing Simple Calculations with C# Telerik Corporation

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 Explicit Type Conversions 9. Expressions 2

Arithmetic, Logical, Comparison, Assignment, Etc.

 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# :  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

CategoryOperatorsArithmetic + - * / % Logical && || ^ ! Binary & | ^ ~ > Comparison == != = Assignment = += -= *= /= %= &= |= ^= >= String concatenation + Type conversion is as typeof Other. [] () ?: new 6

PrecedenceOperatorsHighest() (postfix) new typeof (prefix) + - (unary) ! ~ * / % + - > > = is as = is as == != & Lower^ 8

PrecedenceOperatorsHigher| && || ?: Lowest = *= /= %= += -= >= &= ^= |= 9  Parenthesis operator always has highest precedence  Note: prefer using parentheses, even when it seems stupid to do so

 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 int squarePerimeter = 17; double squareSide = squarePerimeter / 4.0; double squareArea = squareSide * squareSide; Console.WriteLine(squareSide); // 4.25 Console.WriteLine(squareArea); // 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 Console.WriteLine(11.0 / 3); // Console.WriteLine(11 / 3.0); // 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 int bigNum = ; int bigSum = 2 * bigNum; // Integer overflow! Console.WriteLine(bigSum); // bigNum = Int32.MaxValue; bigNum = bigNum + 1; Console.WriteLine(bigNum); // checked{ // This will cause OverflowException // This will cause OverflowException bigSum = bigNum * 2; bigSum = bigNum * 2;}

Live Demo

 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 ) : 17Operation||||||||&&&&&&&&^^^^Operand Operand Result

 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

Live Demo

 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 > move the bits (left or right)  Behavior of the operators |, & and ^ : 21Operation||||&&&&^^^^Operand Operand Result

 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; // ushort b = 5; // Console.WriteLine( a | b); // Console.WriteLine( a & b); // Console.WriteLine( a ^ b); // Console.WriteLine(~a & b); // Console.WriteLine( a << 1); // Console.WriteLine( a >> 1); //

 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; // int mask = 1 << p; // int nAndMask = n & mask; // int bit = nAndMask >> p; // Console.WriteLine(bit); // 1 int p = 5; int n = 35; // int mask = ~(1 << p); // int result = n & mask; // Console.WriteLine(result); // 3

 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; // int mask = 1 << p; // int result = n | mask; // Console.WriteLine(result); // 51 Console.WriteLine( Convert.ToString(result, 2).PadLeft(32, '0')); Convert.ToString(result, 2).PadLeft(32, '0')); //

Live Demo

 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 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

Live Demo

 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

 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

 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

 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

 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

Live Demo

 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;

 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;

 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!

Live Demo

 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 have:  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.

Live Demo

 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

 Boolean algebra (logic)  %28logic%29 %28logic%29 %28logic%29  Bitwise mask  ng%29 ng%29 ng%29  Bitwise operation   Bit Twiddling Hacks  graphics.stanford.edu/~seander/bithacks.html graphics.stanford.edu/~seander/bithacks.html 47

Questions?Questions?

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  true. 5. Write a boolean expression for finding if the bit 3 (counting from 0 ) of a given integer is 1 or Write an expression that checks if given point ( x, y ) is within a circle K( O, 5 ). 49

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

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= 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 ( ), p=3, v=1  13 ( ) n = 5 ( ), p=2, v=0  1 ( ) 51

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