itp2.pptx

40
Operators and expressions

Transcript of itp2.pptx

Page 1: itp2.pptx

Operators and expressions

Page 2: itp2.pptx

Assignment Operator

• x=3– = is an operator– The value of this expression is 3– = operator has a side effect -- assign 3 to x

• The assignment operator =– The side-effect is to assign the value of the right hand

side (RHS) to the left hand side (LHS).– The value is the value of the RHS.

• For example:x = ( y = 3 ) +1; /* y is assigned 3 */

/* the value of (y=3) is 3 */ /* x is assigned 4 */

Page 3: itp2.pptx

Arithmetic operators in C

C operation Algebric CAddition(+) a+7 a+7Subtraction (-) b-c b-cMultiplication(*) am a*mDivision(/) x/y x/yModulus(%) r mod s r%sUnary + +aUnary - -a

An expression is a combination of variables, constants and operators.

Page 4: itp2.pptx

Precedence order • Highest to lowest (left to right in an expression)

• ( )• *, /, %• +, -

Example:z = p * r % q + w / x – y ; 1 2 4 3 5

a * ( b + c ) + c * ( d + e ) ; 3 1 5 4 2

Page 5: itp2.pptx

Operator Precedence and Associativity

highest: + - (unary) * / %lowest: + - (binary)

-i * -j = (-i) * (-j)+i + j / k = (+i) + (j / k)

The binary arithmetic operators (*, /, %, + and -) are all left associative i – j – k = (i – j) – k i * j / k = (i * j) / k

The unary arithmetic operators( + and -) are both right associative-+ i = - ( +i )

left/right associative: it groups from left/right to right/left

Page 6: itp2.pptx

Expression EvaluationPrecedence Name Symbol(s) Associativity

1 X++/X-- left

2 ++X/--Xunary +/-

right

3 multiplicative *, /, % left

4 additive +, - left

5 assignment =, *=, /=, +=, -= right

Page 7: itp2.pptx

Compound(Shorthand) Assignment Operator• Often we use “update” forms of operators

– x=x+1, x=x*2, ...• C offers a short form for this:

– Generic Form : variable op= expr is equivalent to variable = variable op expr

Operator Equivalent to:

x *= y x = x * y

y -= z + 1 y = y - (z + 1)

a /= b a = a / b

x += y / 8 x = x + (y / 8)

y %= 3 y = y % 3

Update forms have value equal to the final value of expri.e., x=3; y= (x+=3); /* x and y both get value 6 */

Page 8: itp2.pptx

TYPE CONFLICTS IN C

• An arithmetic operation between an integer and integer always yields an integer result.

• An operation between a real and real always yields a real result.

• An operation between an integer and real always yields a real result. In this operation the integer is first promoted to a real and then the operation is performed. Hence the result is real.

. Operation Result Operation Result 5 / 2 2 2 / 5 0 5.0 / 2 2.5 2.0 / 5 0.4 5 / 2.0 2.5 2 / 5.0 0.4 5.0 / 2.0 2.5 2.0 / 5.0 0.4

Page 9: itp2.pptx

Type Conversion• C allows for conversions between the

basic types, – implicitly or– explicitly.

Ma

na

v R

ac

hn

a C

olle

ge

of E

ng

g.

Page 10: itp2.pptx

Implicit Conversion• If the compiler expects one type at a position, but another

type is provided, then implicit conversion occurs.

• Conversion during assignments:char c='a';int i;i=c; /* i is assigned the ASCII code of ’a’ */

• Arithmetic conversion – if two operands of a binary operator are not the same type, implicit conversion occurs:

int i=5 , j=1;float x=1.0 , y;y = x / i; /* y = 1.0 / 5.0 */y = j / i; /* y = 1 / 5 so y = 0 */

Page 11: itp2.pptx

Explicit ConversionExplicit conversion uses the cast operator.

• Example :int x=10;float y, z=3.14;y=(float) x; /* y=10.0 */x=(int) z; /* x=3 */

• Example :int i=5 , j=1;float x=1.0 , y;y = (float) j / i; /* y = 1.0 / 5 explicit*/

/* The cast operator has a higher precedence */

Page 12: itp2.pptx

Increment and Decrement• Other operators with side effects are the pre-

and post-increment and decrement operators.– Increment: ++ ++x, x++

• ++x is the same as : (x = x + 1)– Has value xold +1

– Has side-effect of incrementing x• x++

– Has value xold

– Has side-effect of incrementing x

– Decrement -- --x, x--• similar to ++

Page 13: itp2.pptx

Increment and Decrement• a++; or ++a; would be same.• But b=a++; The value of a is assigned to b and then it

incremented• b=++a; is different; The value of a is incremented and then it

assigned to b)• That means, prefix and postfix have different effects when

used in association with some other operator in a C statement.main()

{ int a=10,b=10; printf(“%d ”,a++); printf(“%d”,++b);

}Output :10 11

Page 14: itp2.pptx

Relational Operators• Relational operators allow you to compare two operands (that

can be variables, constants or expressions).– They return a 1 value for true and a 0 for false.Operator Symbol Example

Equals == x == y Greater than > x > yLess than < x < yGreater/equals>= x >= yLess than/equals <= x <= yNot equal != x != y

– 0 as false– 1as true

Page 15: itp2.pptx

Relational Operators

Examples :• a<b• a==b+3• d>=5.66• (p+q)<=(t+r-5)• alpha!=‘t’

int a=10,b=20,c=30,d,e;d=a>b;e=b<=c;d=?, e=?

Page 16: itp2.pptx

Logical Operators

• Combines the results of evaluation of expressions that evaluates to either true or false.

• && AND - true only if two expressions are true.• || OR - true if atleast one of the two

expressions are true.• ! NOT - reverses the value of expression it

operates on.• !,&&, || (order of precedence level),(!- right

associative, &&, || - left associative)Ex.. !((a>1)&&(a<10))||((a<-1)&&(a>-10))

Page 17: itp2.pptx

Operator SummaryM

anav Rachna C

ollege of Engg.

Page 18: itp2.pptx

Operating on Bits (1)

• C allows you to operate on the bit representations of integer and char variables (can’t be applied on floats and doubles). – Generally called bit-wise operators.

• Integers occupy16-bits, numbered from 0 to 15.• Chars occupy 8 bits, therefore bits are numbered 0

to 7.

• 6552010 = 1111 1111 1111 00002

Page 19: itp2.pptx

Operating on Bits (2)

Bitwise operators• The shift operator:

– x << n(left shift)• Shifts the bits in x n positions to the left, shifting in zeros on the

right.• If x = 1111 1111 1111 00002

x << 1 equals 1111 1111 1110 00002

– x >> n(right shift)• Shifts the bits in x n positions right.

– shifts in the sign if it is a signed integer (arithmetic shift) – shifts in 0 if it is an unsigned integer

• x >> 1 is 0111 1111 1111 10002

Page 20: itp2.pptx

Operating on Bits (3)

• Bitwise logical operations– Work on all integer types

• & Bitwise AND (1 1 1) x&y

• | Bitwise Inclusive OR(0 0 0) x|y

• ^ Bitwise Exclusive OR x^y output 1 only if input bits are different

• ~ The complement operator ~ y Complements all of the bits of X

Page 21: itp2.pptx

Bitwise AND and exclusive OR

Single & and | operators (bitwise AND and OR)

work differently from logical AND and OR

( && and || ). You can think of the logical operators

as returning a single 1 for true, and 0 for false.

The purpose of the & and | bitwise operators is to

return a resulting set of output 1s and 0s based on

the boolean AND or OR operations between

corresponding bits of the input.

Page 22: itp2.pptx

Bitwise exclusive OR operator

Symbol: ^

For each bit of output, this output is a 1 if 0 0 0

corresponding bits of input are different, and the 0 1 1

output is a 0 if the input bits are the same. 1 0 1

1 1 0• One's complement operator:Symbol: ~

This is a unary operator in the sense that it works

on a single input value. The bit pattern output is

the opposite of the bit pattern input with input 1s

becoming output 0s and input 0s becoming output

1s.

Page 23: itp2.pptx

Shift, Multiplication and Division

• Multiplication and division is often slower than shift.• Multiplying 2 can be replaced by shifting 1 bit to the

left.n = 10printf(“%d = %d” , n*2, n<<1);printf(“%d = %d”, n*4(2power2), n<<2);……(ex. a=45, a<<2=45*2power2 =180(0000 0000 1011 0100))

• Division by 2 can be replace by shifting 1 bit to the right.n = 10printf(“%d = %d” , n/2, n>>1);printf(“%d = %d”, n/4, n>>2);

Page 24: itp2.pptx

Operator PrecedenceOperator Precedence level

( ) 1~, ++, --, unary - 2*, /, % 3+, - 4<<, >> 5<, <=, >, >= 6==, != 7& 8

^ 9 | 10

&& 11|| 12=, +=, -=, etc. 13

We’ll be adding more to this list later on...

Page 25: itp2.pptx

An Example• What is the difference between the two lines of output?

#include <stdio.h>int main (){ int w=10,x=20,y=30,z=40; int temp1, temp2; temp1 = x * x /++y + z / y; printf ("temp1= %d;\nw= %d;\nx= %d;\ny= %d;\nz= %d\n",

temp1, w,x,y,z); y=30; temp2 = x * x /y++ + z / y; printf ("temp2= %d;\nw= %d;\nx= %d;\ny= %d;\nz= %d\n",

temp2, w,x,y,z); return 0;}

Page 26: itp2.pptx

Conditional Operator• The conditional operator essentially allows you to embed an “if” statement into an

expression• Generic Form

exp1 ? exp2 : exp3 if exp1 is true (non-zero)value is exp2(exp3 is not evaluated)

if exp1 is false (0),value is exp3(exp2 is not evaluated)

• Example:z = (x > y) ? x : y;

• This is equivalent to:if (x > y)

z = x;else

z = y;

Page 27: itp2.pptx

Comma Operator• An expression can be composed of multiple

subexpressions separated by commas.– Subexpressions are evaluated left to right.– The entire expression evaluates to the value of the

rightmost subexpression.• Example:

x = (++a, b++);• a is incremented• b is assigned to x• b is incremented

– Parenthesis are required because the comma operator has a lower precedence than the assignment operator!

• The comma operator is often used in for loops.

Manav R

achna College of E

ngg.

Page 28: itp2.pptx

Comma Operator and For Loop

• Example:• int i, sum;• for (i=0,sum=0;i<100;i++){• sum += i;• }• printf(“1+...+100 = %d”, sum);

Page 29: itp2.pptx

Type Definitions

typedef int BOOLBOOL flag; /* same as int flag; */

typedef short int Int16typedef long int Int32typedef unsigned char Byte

typedef struct {int age; char *name} person; person people;

Page 30: itp2.pptx

Formatted Input/Outputprintf function

printf(string, expr1, expr2, ……..)

string: ordinary characters and conversion specifications (%) %d --- int %s --- string %f --- float

printf(“i=%d, j=%d. x=%f\n”, i, j, x);

Page 31: itp2.pptx

Formatted Input/Output

Conversion Specification%[-]m.pX

m: specifies the minimum number of characters to print. %4d-- _123; %-4--123_

p: depends on the choice of X

X: -d: decimal form -e: floating-point number in exponential format -f: floating-point number in “fixed decimal” format -g: either exponential format or fixed decimal format, depending on the number’s size

Page 32: itp2.pptx

Formatted Input/Outputmain(){ int i = 40; float x = 839.21; printf(“|%d|%5d|%-5d|%5.3d|\n”, i, i, i, i); printf(“|%10.3f|%10.3e|%-10g|\n”, x, x, x);}

Page 33: itp2.pptx

Formatted Input/OutputEscape Sequence

Enable strings to contain characters that would otherwise causeproblems for the compiler

alert \a new line \n \” “backspace \b horizontal tab \t \\ \

Page 34: itp2.pptx

Formatted Input/OutputHow scanf works: is controlled by the conversion specificationIn the format string starting from left to right.When called, it tries to locate an item of the appropriate typeIn the input data, skipping white-space characters(the space, Horizontal and vertical tab, form-feed, and new-line character)

scanf(“%d%d%f%f”, &i, &j, &x, &y);input:___1-20___.3___-4.0e3

___1*-20___.3*___-4.0e3*sss r s rrr sss rrs sss rrrrrr

Page 35: itp2.pptx

Ordinary Characters in Format String

White-space characters: one white-space character in the format string will match any number of white-space character in the input.

Other characters: when it encounters a non-white-space character in a format string, scanf compares it with the next input character. If the two characters match, scanf discards the input character and continues processing the format string. Otherwise, scanf puts the offending character back into the input, then aborts without futher processing.

%d/%d will match _5/_96, but not _5_/_96%d_/%d will match _5_/_96

Page 36: itp2.pptx

Variable TypeC has the following simple data types:

Page 37: itp2.pptx

Variable Type

Java has the following simple data types:

Page 38: itp2.pptx

Basic TypesType (16 bit) Smallest Value Largest Value

short int -32,768(-215) 32,767(215-1)

unsigned short int 0 65,535(216-1)

Int -32,768 32,767

unsigned int 0 65,535

long int -2,147,483,648(-231) 2,147,483,648(231-1)

unsigned long int 0 4,294,967,295

Page 39: itp2.pptx

Basic TypesType (32 bit) Smallest Value Largest Value

short int -32,768(-215) 32,767(215-1)

unsigned short int 0 65,535(216-1)

Int -2,147,483,648(-231) 2,147,483,648(231-1)

unsigned int 0 4,294,967,295

long int -2,147,483,648(-231) 2,147,483,648(231-1)

unsigned long int 0 4,294,967,295

Page 40: itp2.pptx

Floating Typesfloat single-precision floating-pointdouble double-precision floating-point long double extended-precision floating-point

Type Smallest Positive Value

Largest Value Precision

float 1.17*10-38 3.40*1038 6 digits

double 2.22*10-308 1.79*10308 15 digits

double x; long double x;scanf(“%lf”, &x); scanf(“%Lf”, &x);printf(“%lf”, x); printf(“%Lf”, x);