1 / 40

by A. Ramkumar (Asst. Prof.) Dept. of Commerce With CA

OPERATORS AND EXPRESSIONS. by A. Ramkumar (Asst. Prof.) Dept. of Commerce With CA. Operators and Expressions.

igoodin
Download Presentation

by A. Ramkumar (Asst. Prof.) Dept. of Commerce With CA

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. OPERATORS AND EXPRESSIONS byA. Ramkumar (Asst. Prof.)Dept. of Commerce With CA

  2. Operators and Expressions • An operator is a symbol or letter used to indicate a specific operation on variables in a program. Example, the symbol `+' is an add operator that adds two data items called operands. • Expression.An expression is a combination of operands (i.e., constants, variables, numbers) connected by operators and parentheses. Example, in the expression given below, A and B are operands and `+' is an operator. A + B • An expression that involves arithmetic operators is known as an arithmetic expression. • The computed result of an arithmetic expression is always a numerical value. • An expression which involves relational and/or logical operators is called a Boolean expression or logical expression. • The computed result of such an expression is a logical value, i.e., either 1 (True) or 0 (False).

  3. Rules for Formation of an Expression • A signed or unsigned constant or variable is an expression. • An expression connected by an operator to a variable or a constant is an expression. • Two expressions connected by an operator also form an expression. • Two operators should not occur in continuation.

  4. Arithmetic Operators • Arithmetic operators can further be classified as unary operators and binary operators. Arithmetic operators

  5. Binary Arithmetic Operators • The binary arithmetic operators supported by C are addition, subtraction, multiplication, division, and modulus or remainder. • They are called binary operators because they require two operands to work with. • The evaluations of binary operators is left associative. • Operators of the same level are evaluated from left to right.

  6. Unary Arithmetic Operators • A unary operator requires only one operand or data item. • The unary arithmetic operators supported by C are, unary minus (‘–’), increment (‘++’), and decrement (‘––’). • Compared to binary operators, the unary operators are right associative in the sense that they evaluate from right to left. • The operators ‘++’ and ‘––’ are unique to C. • These are called increment and decrement operators respectively. The increment operator ++ adds 1 to its operand. Therefore we can say that the following expressions are equivalent. i = i +1 ; ≡ ++i

  7. Arithmetic with Characters • A peculiar aspect of C is that arithmetic operations can also be performed with characters as shown in the following program segment. : char ch; ch = `A'; ch = ch + 1; printf ("ch = % c", ch); : The output of this program segment would be: ch= B

  8. Type Combination and Promotion • Different data types can be mixed together in arithmetic expressions. • For instance, int and float can be combined in an expression as shown below: intx = 10; float y = 9.2; y = y + x; • Whenever the complier encounters such expressions, it promotes the smaller sized operand to the same size as that of the larger size operand. Thus, in the above expression x (int) is promoted to a float and then added to y.

  9. Truncation • When values from a bigger type are moved by the assignment operator to a smaller type, truncation takes place. Consider the following program segment: char ch; intval = 329; ch= val; printf("\n % c, %d," ch, ch); The output of the above segment would be: I, 73. It may noted that while moving the value contained in val (i.e. 329) to ch, the assignment operator has dropped upper bits of val. The lower bits of val (329) represent 329 – 256 = 73. The ASCII equivalent of 73 is 'I'.

  10. Key Points • The division of an integer by another integer always results in an integer value. Example:the result of 5/2 is 2 (the decimal portion of the result is dropped). • If both or one of the operands in a division operation is a floating point, the result is always a floating point. Example:the result of 15/2.0 is 7.5. • The remainder operator % produces the remainder of an integer division. For example, the result of 5 % 2 is 1. This operator cannot be used with floating point numbers.

  11. Relational and Logical Operators • A relational operator is used to compare two values and the result of such an operation is always logical, i.e., either true or false. • The valid relational operators supported by C are given below:

  12. Logical Operators • A logical operator is used to connect two relational expressions or logical expressions. • The result of such an operation is always logical, i.e., either True (1) or False (0). The valid logical operators supported by C are given below:

  13. Rules of Logical Operators • The output of a logical AND operation is true if both its operands are true. For all other combinations, the result is false. • The output of a logical OR operation is false if both of its operands are false. For all other combinations the result is true. • The logical NOT is a unary operator. It negates the value of the operand.

  14. Conditional Operator • C provides a conditional operator (? :) which can help the programmers in performing simple conditional operations. • It is represented by the symbols '?' and ':' • The general form of this operation is: E1 ? E2 : E3 where E1, E2 and E3 are expressions. • In the conditional operation, the expression E1 is tested; if E1 is true then E2 is evaluated; otherwise the expression E3 is evaluated, as shown below: Conditional operator

  15. Example Write a program that reads two integers x and y. It prints 'x is greater' if x > y and 'y is greater' otherwise? Solution : We will use conditional expression in this program.

  16. Order of Evaluation of Expressions • A number of logical and relational expressions can be linked together with the help of logical operators, as shown below: (x < y) || (x > 20) && !(z) || ((x < y) && (z > 5)) • For a complex expression such as the one given above, it becomes difficult to make out the order in which the evaluation of sub expressions would take place in. • In C, the order of evaluation of an expression is according to the operator precedence given below: • It may be noted here that in C, false is represented as zero and true as any non-zero value. Thus, expressions that use relational and logical operators return either 0 (false) or 1 (true).

  17. Key Points when Working with Relational and Logical Operators 1. Relational operators have lower precedence as compared to arithmetic operators. Therefore, the expression 5 > 10 + 1 is evaluated as if it were written as 5 > (10 + 1) and not as (5 > 10) + 1 2. One very common error that C programmers make is that they use the assignment operator (=) in place of the equality operator (==). The distinction between the two is worth mentioning. For example, the statement val= 5; assigns a value 5 to variable val, whereas the statement (val == 5) checks whether val is equal to 5 or not. If the expression is true, the result is 1 otherwise it is 0. 3. It may be noted here that using the operator `=' in place of `==' is not a syntax error but a logical error. You should avoid equality and inequality comparisons using floating point numbers because floating point arithmetic is not as exact as integer arithmetic.

  18. Key Points when Working with Relational and Logical Operators (contd.) 4. Relational operators are grouped left to right i.e the expression a < b < c implies (a < b ) < c and not a < ( b < c ) 5. The relational operators have higher precedence over the logical operators (&& and !!). In the following expression ((a == 5) && ( b == 10)) the inner parentheses are not required because they will automatically be evaluated first. However, the logical NOT operator (!) has even higher precedence than relational or arithmetic operators. 6. Evaluation of a logical expression is also from left to right and the evaluation stops as soon as the final outcome can be determined.

  19. Points Regarding Conditional Operators • The conditional operator has a lower precedence as compared to all other operators that we have discussed, i.e., arithmetic, relational and logical. • The conditional expressions could be nested, i.e., expression 2 and expression 3 instead of being values, could be expressions using conditional operators. • The order of evaluation of the ‘? :’ operator depends upon the outcome of the leftmost operand which is evaluated first. If it is true, the middle operand is evaluated and the last one ignored. If it is false, the last operand is evaluated and the middle one ignored.

  20. Example Q)Determine the order of evaluation of the following expression A && ! B Solution: The order of evaluation is given below It may be noted that the logical NOT (i.e.,!) is a unary operator and it requires only one operand. It is suggested that parentheses should be used to enhance the readability of the expression. For example, the expression A && ! B can be written as shown below: A && (! B)

  21. Type Conversion in Expressions • C provides type casting facility i.e., to convert an expression to be of a specific type. • It is useful in a situation where the expression on the right hand side of an assignment operator is of a different type compared to the type of the variable on the left hand side of the assignment operator. • Mixed mode expressions can also be handled by this feature of C. The format of a cast is: (type) expression where type : is a valid C data type. Examples of valid type casts are : (i) int x = 5; float y; y = (float) x + 3.9; (ii) int z; z = (int) 3.1415;

  22. Handling Complex Expressions • The solution to complex mathematical expressions is to suitably parenthesize the sub expressions appearing within the complex expression at hand. Thereafter, write the parenthesized sub-expressions in a ‘C’ expression in left-to-right and top-to-bottom fashion. Example:

  23. sizeof Operator • C provides a compile time unary operator called sizeof, that when applied on an operand, returns the number of bytes the operand occupies in the main memory. The operand could be a variable, a constant or a data type. For example, the following expressions: int sum; a = sizeof (sum); b = sizeof (char); c = sizeof (123L); would return the sizes occupied by variable sum, data type char and constant `123L' in a program. NOTE: • The parentheses used with sizeof are required when the operand is a data type. However, with variables or constants, the parentheses are not necessary. • The sizeof operator has the same precedence as prefix increment/decrement operators.

  24. Comma Operator • The comma operator is used to string together a number of expressions which are performed in a sequence from left to right. For example, the following statement a = (x = 5, x + 2); executes in the following order: (i) a value 5 is assigned to variable x. (ii) x is incremented by 2. (iii) the value of expression x + 2 (i.e. 7) is assigned to the variable a. The following points may be noted regarding comma operators. • A list of expressions, separated by comma, is always evaluated from left to right. • The final value and type of a comma separated list of expressions is always the same as the type and value of the rightmost expression in the list. • The comma operator has the lowest precedence among all C operators.

  25. Assignment Statement • An assignment statement assigns the value of the expression on the right hand side to a variable on the left hand side of the assignment operator (=). • Its general form is given below: < variable name > = < expression > • The variable on the left side of the assignment operator is also called lvalue and is an accessible address in the memory. Expressions and constants on the right side of the assignment operator are called rvalues. • Multiple assignments in a single statement can be used, especially when the same value is to be assigned to a number of variables. a = b = c = 30; A point worth noting is that C converts the type of the value on the right hand side to the data type on the left.

  26. Variable Initialization • You can initialize a variable at the time of declaration or in a separate statement after it is declared. For example, if a variable Z is to be initialized with a value 10, we can use any of the following ways (a) int Z; Z = 10; (b) int Z = 10; • C also allows you to assign the same value to many variables in a single statement using multiple assignments. int a, b, c; a = b = c = 0; • If more than one variable is to be initialized with different values, we can provide a comma separated list as follows: inta = 5, b = 10, c = 15;

  27. Compound Assignment Operator (Expression Shorthands) • In addition to the standard assignment operator ('='), C also supports compound assignment operators as listed below: + = – = * = / = % = The general form of a compound assignment expression is: <var> op = E; where < var> : is a variable op : is a compound assignment operator E : is a valid arithmetic expression. Consider the following assignment expression: total_sal_of_emp= total_sal_of_emp * 1.5; This expression can be simplified as shown below: total_sal_of_emp*= 1.5;

  28. Bitwise Operators • C, being system programming language, supports bitwise operators. • These operators are used for the manipulation of integer data items at bit level. • A table of bitwise operators supported by C is given below:

  29. Bitwise Shift Operators • C supports special bitwise shift operators: shift left (< <) and shift right (> >) operators. • Such data at machine level is represented in the binary form; it can be shifted to the left or right by these special operators. • However, the number of bits to be shifted is specified by an integer written next to the operator, as shown below:

  30. Left Shift Operators X << 3 The above statement means that the value contained in x is shifted to the left by 3 bits. Thus, the leftmost 3 bits of X will be lost and the resultant rightmost 3 vacant bits will be filled by zeros, as shown in below: Left shift operator

  31. Right Shift Operator Y >> 2 In this case the rightmost two bits would be lost and the resultant leftmost 2 vacant bits would be filled by zeros, as shown below: It may be noted that the shift operations are carried out in temporary locations whereas the original contents of the variables remain intact. Right shift operator

  32. Example For instance, consider the following program: # include <stdio.h> main() { int x = 8; printf("\n %d %d", x>>1, x); } The output of above program is: 4 8. The first output 4 indicates that the contents of x have been shifted by one bit to the right but the operation has been done in a temporary location. The second output 8 indicates that the contents of the variable x have remained intact.

  33. Bitwise Logical Operators • The bitwise AND (&) operator takes two operands and produces a bitwise logical AND with them. For example, consider the following program: • The binary representation of x (5) is ‘101’ and that of y (7) is ‘111’. The logical bitwise AND of x and y will produce ‘101’ which is 5. Therefore, the output of above program is : z = 5.

  34. Bitwise OR Operator The bitwise OR ( | ) operator takes two operands and produces their bitwise logical OR. For example, consider the following program: The binary representation of x (5) is ‘101’ and that of y (7) is ‘111’. The logical bitwise OR of x and y will produce ‘111’ which is 7. Therefore, the output of above program is : z = 7.

  35. Bitwise XOR Operator The bitwise XOR (^) operator takes two operands and produces their bitwise logical XOR. For example, consider the following program: The binary representation of x (5) is ‘101’ and that of y (7) is ‘111’. The logical bitwise XOR of x and y will produce ‘010’ which is 2. Therefore, the output of above program is : z = 2.

  36. Bitwise Assignment Operators There are two more variations of assignment operators called ‘Bitwise right shift assignment operator (>>=)’ and ‘Bitwise left shift assignment operator (<<=)’. • Bitwise left shift assignment operator (<<=) • Bitwise Right shift assignment operator (>>=)

  37. Bitwise Left Shift assignment operator (<<=) This operator is a combination of the left shift operator and an assignment operator. Consider the following expression: val<<= 2; The above expression left shifts the contents of variable val by 2 bits and stores the new contents back into val itself.

  38. Bitwise Right Shift Assignment Operator (>>=) This operator is a combination of the right shift operator and an assignment operator. Consider the following expression: num>>= 3; The above expression right shifts the contents of the variable num by 3 bits and stores the new contents back into num itself.

  39. One’s (1’s) Complement Operator (~) From our knowledge of binary arithmetic, we know that subtraction (x − y) is carried out by adding the 2’s complement of the second operand (i.e., y) to the first operand (i.e., x). The 2’s complement is obtained by ORing 1 to the 1’s complement of y. The 1’s complement can be obtained by using the ‘~’ operator of C . For example, the following statement will produce 1’s complement of ‘y’, an integer variable. int y =5; y = ~ y; The following statement would give the 2’s complement of y. y = y | 1;

  40. Example The following program would print y = −5, that is, the 2’s complement of y or the negation of variable y.

More Related