Sunday, July 29, 2012

STRINGS OPERATORS AND EXPRESSIONS ON C# . [DOT] NET


STRINGS OPERATORS AND EXPRESSIONS
                                       ON C# . [DOT] NET                                        

Strings

•         Reference type
•         Represents a string of Unicode characters
string studentName;
string courseName = "Programming I";
string twoLines = “Line1\nLine2”;             
   
Making Data Constant

•         Add the keyword const to a declaration
•         Value cannot be changed 
•         Standard naming convention
•         Syntax
–        const type identifier = expression;
const double TAX_RATE = 0.0675; 
const int SPEED = 70;
const char HIGHEST_GRADE = ‘A’; 

Assignment Statements

•         Used to change the value of the variable
–        Assignment operator (=) 
•         Syntax
variable = expression;
•         Expression can be:
–        Another variable
–        Compatible literal value
–        Mathematical equation
–        Call to a method that returns a compatible value
–        Combination of one or more items in this list

Examples of Assignment Statements

double accountBalance, weight;
decimal amountOwed, deficitValue;
bool isFinished;

accountBalance = 4783.68;
weight = 1.7E-3;                  //scientific notation may be used
amountOwed = 3000.50m; // m or M must be suffixed to
                                            // decimal
deficitValue = -322888672.50M;

isFinished = false;      
int        count = 0, newValue = 25;
string aSaying, fileLocation;

aSaying = “First day of the rest of your life!\n ";
fileLocation = @”C:\CSharpProjects\Chapter2”;
// declared previously as a bool
count = newValue;


@ placed before a string literal signals that the characters inside the double quotation marks should be interpreted verbatim



Figure 3-5 Impact of assignment statement




Arithmetic Operations

•         Simplest form of an assignment statement
                        resultVariable = operand1 operator operand2;
•         Readability
–        Space before and after every operator 


+ Operator on a StringConcatenation



Fundamental Precedence Order of operators

•         Precedence order from high to low
               ( )                  - elements within parentheses
               *, /, %           - multiplicative
                  +, -             - additive
•         Computation proceeds from left to right (left associative) within each precedence category
•         Increment and Decrement Operations
–        Unary operator
                        num++;     // num = num + 1;                         
                        --value1;   // value = value – 1;
–        Preincrement/predecrement versus post                                 
int num = 30;
System.Console.WriteLine(num++);  // Displays 30
System.Console.WriteLine(num);      // Display 31
System.Console.WriteLine(--num); // Displays 30

Compound Operations

•         Accumulation
–        +=



Order of Operations

•         Parentheses () – above *, / and % in precedence


•         Associativity of operators
–        Left
–        Right

Mixed Expressions

•         Implicit type coercion
–        Changes int data type into a double
–        No implicit conversion from double to int



Figure 3-12 Syntax error generated for assigning a double to an int


         Explicit type coercion
        Cast
        (type) expression
        examAverage = (exam1 + exam2 + exam3) / (double) count;

int value1 = 0, anotherNumber = 75;
double  value2 = 100.99, anotherDouble = 100;
value1 = (int) value2;      // value1 = 100
value2 = (double) anotherNumber;   // value2 = 75.0

Formatting Output

         You can format data by adding dollar signs, percent symbols, and/or commas to separate digits
         You can suppress leading zeros
         You can pad a value with special characters
        Place characters to the left or right of the significant digits
         Use format specifiers

Numeric Format Specifiers



Custom Numeric Format Specifiers



Formatting Output :



What is an Expression?

         The most basic expression consists of an operator, two operands and an assignment. The following is an example of an expression:
         int theResult = 1 + 2; In the above example the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to an integer variable namedtheResult. The operands could just have easily been variables or constants (or a mixture of each) instead of the actual numerical values used in the example.
         In the remainder of this chapter we will look at the various types of operators available in C#.

The Basic Assignment Operator

         We have already looked at the most basic of assignment operators, the = operator. This assignment operator simply assigns the result of an expression to a variable. In essence the = assignment operator takes two operands. The left hand operand is the variable to which a value is to be assigned and the right hand operand is the value to be assigned. The right hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation. The following examples are all valid uses of the assignment operator:
         x = 10; // Assigns the value 10 to a variable named x x = y + z; // Assigns the result of variable y added to variable z to variable x x = y; // Assigns the value of variable y to variable x Assignment operators may also be chained to assign the same value to multiple variables. For example, the following code example assigns the value 20 to the x, y and z variables:
         int x, y, z; x = y = z = 20;

C# Arithmetic Operators

         C# provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-) which serves to indicate that a value is negative rather than positive. This contrasts with the subtraction operator (-) which takes two operands (i.e. one value to be subtracted from another). For example:
         int x = -10; // Unary - operator used to assign -10 to a variable named x x = y - z; // Subtraction operator. Subtracts z from y




         Note that multiple operators may be used in a single expression.
         For example:
         x = y * 10 + z - 5 / 4; Whilst the above code is perfectly valid it is important to be aware that C# does not evaluate the expression from left to right or right to left, but rather in an order specified by the precedence of the various operators. Operator precedence is an important topic to understand since it impacts the result of a calculation and will be covered in detail the next section.


C# Operator Precedence

         When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:
         10 + 20 * 10 = 300
         This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask C# to perform the same calculation and you get a very different answer:
         int x; x = 10 + 20 * 10; System.Console.WriteLine (x) The above code, when compiled and executed, will output the result 210.
         This is a direct result of operator precedence. C# has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, C# considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.
         Fortunately the precedence built into C# can be overridden by surrounding the lower priority section of an expression with parentheses. For example:
         int x; x = (10 + 20) * 10; System.Console.WriteLine (x) In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in a value of 300.
         The following table outlines the C# operator precedence order from highest precedence to lowest:




Compound Assignment Operators




         C# provides a number of operators designed to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, one might write an expression as follows:
         x = x + y; The above expression adds the value contained in variable x to the value contained in variable y and stores the result in variable x. This can be simplified using the addition compound assignment operator:
         x += y The above expression performs exactly the same task as x = x + y but saves the programmer some typing. 

 Comparison Operators:



         n addition to mathematical and assignment operators, C# also includes set of logical operators useful for performing comparisons. These operators all return a Boolean (booltrue or false result depending on the result of the comparison. These operators are binary in that they work with two operands.
         Comparison operators are most frequently used in constructing program flow control. For example an if statement may be constructed based on whether one value matches another:
         if (x == y) System.Console.WriteLine ("x is equal to y"); The result of a comparison may also be stored in a bool variable. For example, the following code will result in a true value being stored in the variable result:
         bool result; int x = 10; int y = 20; result = x < y;

Boolean Logical Operators

         Another set of operators which return boolean true and false values are the C# boolean logical operators. These operators both return boolean results and take boolean values as operands. The key operators are NOT (!), AND (&&), OR (||) and XOR (^).
         The NOT (!) operator simply inverts the current value of a boolean variable, or the result of an expression. For example, if a variable named flag is currently true, prefixing the variable with a '!' character will invert the value to be false:
         bool flag = true; //variable is true bool secondFlag; secondFlag = !flag; // secondFlag set to false The OR (||) operator returns true if one of its two operands evaluates to true, otherwise it returns false. For example, the following example evaluates to true because at least one of the expressions either side of the OR operator is true:
         if ((10 < 20) || (20 < 10)) System.Console.WriteLine("Expression is true"); The AND (&&) operator returns true only if both operands evaluate to be true. The following example will return false because only one of the two operand expressions evaluates to true:
         if ((10 < 20) && (20 < 10)) System.Console.WriteLine("Expression is true"); The XOR (^) operator returns true if one and only one of the two operands evaluates to true. For example, the following example will return true since only one operator evaluates to be true:
         if ((10 < 20) ^ (20 < 10)) System.Console.WriteLine("Expression is true"); If both operands evaluated to be true, or both were false the expression with return false.

The Ternary Operator

         C# uses something called a ternary operator to provide a shortcut way of making decisions. The syntax of the ternary operator is as follows:
         [condition] ? [true expression] : [false expression]
         The way this works is that [condition] is replaced with an expression that will return either true or false. If the result is true then the expression that replaces the [true expression] is evaluated. Conversely, if the result was false then the [false expression] is evaluated. Let's see this in action:
         int x = 10; int y = 20; System.Console.WriteLine( x > y ? x : y );

No comments:

Post a Comment

Slider

Image Slider By engineerportal.blogspot.in The slide is a linking image  Welcome to Engineer Portal... #htmlcaption

Tamil Short Film Laptaap

Tamil Short Film Laptaap
Laptapp

Labels

About Blogging (1) Advance Data Structure (2) ADVANCED COMPUTER ARCHITECTURE (4) Advanced Database (4) ADVANCED DATABASE TECHNOLOGY (4) ADVANCED JAVA PROGRAMMING (1) ADVANCED OPERATING SYSTEMS (3) ADVANCED OPERATING SYSTEMS LAB (2) Agriculture and Technology (1) Analag and Digital Communication (1) Android (1) Applet (1) ARTIFICIAL INTELLIGENCE (3) aspiration 2020 (3) assignment cse (12) AT (1) AT - key (1) Attacker World (6) Basic Electrical Engineering (1) C (1) C Aptitude (20) C Program (87) C# AND .NET FRAMEWORK (11) C++ (1) Calculator (1) Chemistry (1) Cloud Computing Lab (1) Compiler Design (8) Computer Graphics Lab (31) COMPUTER GRAPHICS LABORATORY (1) COMPUTER GRAPHICS Theory (1) COMPUTER NETWORKS (3) computer organisation and architecture (1) Course Plan (2) Cricket (1) cryptography and network security (3) CS 810 (2) cse syllabus (29) Cyberoam (1) Data Mining Techniques (5) Data structures (3) DATA WAREHOUSING AND DATA MINING (4) DATABASE MANAGEMENT SYSTEMS (8) DBMS Lab (11) Design and Analysis Algorithm CS 41 (1) Design and Management of Computer Networks (2) Development in Transportation (1) Digital Principles and System Design (1) Digital Signal Processing (15) DISCRETE MATHEMATICS (1) dos box (1) Download (1) ebooks (11) electronic circuits and electron devices (1) Embedded Software Development (4) Embedded systems lab (4) Embedded systems theory (1) Engineer Portal (1) ENGINEERING ECONOMICS AND FINANCIAL ACCOUNTING (5) ENGINEERING PHYSICS (1) english lab (7) Entertainment (1) Facebook (2) fact (31) FUNDAMENTALS OF COMPUTING AND PROGRAMMING (3) Gate (3) General (3) gitlab (1) Global warming (1) GRAPH THEORY (1) Grid Computing (11) hacking (4) HIGH SPEED NETWORKS (1) Horizon (1) III year (1) INFORMATION SECURITY (1) Installation (1) INTELLECTUAL PROPERTY RIGHTS (IPR) (1) Internal Test (13) internet programming lab (20) IPL (1) Java (38) java lab (1) Java Programs (28) jdbc (1) jsp (1) KNOWLEDGE MANAGEMENT (1) lab syllabus (4) MATHEMATICS (3) Mechanical Engineering (1) Microprocessor and Microcontroller (1) Microprocessor and Microcontroller lab (11) migration (1) Mini Projects (1) MOBILE AND PERVASIVE COMPUTING (15) MOBILE COMPUTING (1) Multicore Architecute (1) MULTICORE PROGRAMMING (2) Multiprocessor Programming (2) NANOTECHNOLOGY (1) NATURAL LANGUAGE PROCESSING (1) NETWORK PROGRAMMING AND MANAGEMENT (1) NETWORKPROGNMGMNT (1) networks lab (16) News (14) Nova (1) NUMERICAL METHODS (2) Object Oriented Programming (1) ooad lab (6) ooad theory (9) OPEN SOURCE LAB (22) openGL (10) Openstack (1) Operating System CS45 (2) operating systems lab (20) other (4) parallel computing (1) parallel processing (1) PARALLEL PROGRAMMING (1) Parallel Programming Paradigms (4) Perl (1) Placement (3) Placement - Interview Questions (64) PRINCIPLES OF COMMUNICATION (1) PROBABILITY AND QUEUING THEORY (3) PROGRAMMING PARADIGMS (1) Python (3) Question Bank (1) question of the day (8) Question Paper (13) Question Paper and Answer Key (3) Railway Airport and Harbor (1) REAL TIME SYSTEMS (1) RESOURCE MANAGEMENT TECHNIQUES (1) results (3) semester 4 (5) semester 5 (1) Semester 6 (5) SERVICE ORIENTED ARCHITECTURE (1) Skill Test (1) software (1) Software Engineering (4) SOFTWARE TESTING (1) Structural Analysis (1) syllabus (34) SYSTEM SOFTWARE (1) system software lab (2) SYSTEMS MODELING AND SIMULATION (1) Tansat (2) Tansat 2011 (1) Tansat 2013 (1) TCP/IP DESIGN AND IMPLEMENTATION (1) TECHNICAL ENGLISH (7) Technology and National Security (1) Theory of Computation (3) Thought for the Day (1) Timetable (4) tips (4) Topic Notes (7) tot (1) TOTAL QUALITY MANAGEMENT (4) tutorial (8) Ubuntu LTS 12.04 (1) Unit Wise Notes (1) University Question Paper (1) UNIX INTERNALS (1) UNIX Lab (21) USER INTERFACE DESIGN (3) VIDEO TUTORIALS (1) Virtual Instrumentation Lab (1) Visual Programming (2) Web Technology (11) WIRELESS NETWORKS (1)

LinkWithin