itp2.pptx
-
Upload
sushil-pant -
Category
Documents
-
view
213 -
download
0
Transcript of itp2.pptx
Operators and expressions
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 */
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.
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
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
Expression EvaluationPrecedence Name Symbol(s) Associativity
1 X++/X-- left
2 ++X/--Xunary +/-
right
3 multiplicative *, /, % left
4 additive +, - left
5 assignment =, *=, /=, +=, -= right
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 */
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
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.
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 */
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 */
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 ++
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
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
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=?
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))
Operator SummaryM
anav Rachna C
ollege of Engg.
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
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
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
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.
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.
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);
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...
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;}
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;
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.
Comma Operator and For Loop
• Example:• int i, sum;• for (i=0,sum=0;i<100;i++){• sum += i;• }• printf(“1+...+100 = %d”, sum);
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;
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);
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
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);}
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 \\ \
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
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
Variable TypeC has the following simple data types:
Variable Type
Java has the following simple data types:
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
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
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);