0% found this document useful (0 votes)
12 views

Chap 3

The document discusses various operators in C and their usage. It describes arithmetic, relational, logical, assignment, increment/decrement, conditional and bitwise operators. It provides examples of how each operator is used and the output.

Uploaded by

Rahul Prasad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Chap 3

The document discusses various operators in C and their usage. It describes arithmetic, relational, logical, assignment, increment/decrement, conditional and bitwise operators. It provides examples of how each operator is used and the output.

Uploaded by

Rahul Prasad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Operators and Expression

• C supports rich set of built in operators


• An operator is a symbol that tells the computer to perform certain
mathematical and logical manipulations.
• Operators are used in programs to manipulate data and variables.
• They usually forms a part of the mathematical or logical expressions.
• An expression is a sequence of operands and operators that reduces
to a single value.
• C operators can be classified into a number of categories. They
include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic Operators
• C provides all basic arithmetic operators.
• The operators +,-,*,/ all work the same way as they do in other
languages.
• This can operate on any built in data type allowed in C.
• The unary minus operator, in effect, multiplies its single operand by
-1.
• Integer division truncates any fractional part.
• The modulo division operation(%) produces the remainder of an
integer division.
Operator Description Example a=20,b=10 Output
+ Addition a+b 20+10 30
- subtraction a-b 20-10 10
* multiplication a*b 20*10 200
/ Division a/b 20/10 2(quotient)
% Modular a%b 20%10 0 (remainder)
Division
• Integer arithmetic
• When both the operands in a single arithmetic expression are integers, the
expression is called an integer expression, and the operation is called integer
arithmetic.
• Integer arithmetic always yields an integer value.
14/4 = 3(decimal part truncated)
• Write a program to convert given number of days into months and days
• Real arithmetic:
• An arithmetic operation involving only real operands is called real arithmetic.
• A real operand may assume values either in decimal or exponential notation.
• If x,y and z are floats, then we will have:
x = 6.0/7.0 = 0.857143
y = 1.0/3.0 = 0.333333
z = -2.0/3.0 = -0.666667
• The operator % cannot be used with real operands.
• Mixed mode arithmetic
• When one of the operands is real and the other is integer, the expression is
called a mixed mode arithmetic.
• If either operand is of real type, then only the real operation is performed and
the result is always a real number.
15/10.0 = 1.5
• Whereas
15/10 = 1
Relational operator
• Comparison between two entities are done using relational operator.
• An expression containing a relational operator is termed as relational
expression.
• The value of relational expression is either one or zero.
• It is one if the specified relation is true and zero if the relation is false
• C supports six relational operators
Operator Description Example a=20,b=10 Output

< less than a<b 10<20 1


<= less than (or) equal a<=b 10<=20 1
to

> greater than a>b 10>20 0

>= greater than (or) a>=b 10>=20 0


equal to

== equal to a==b 10==20 0


!= not equal to a!=b 10!=20 1
• A simple relational expression contains only one relational operator and
takes the following form:
ae-1 relational operator ae-2
• ae-1 and ae-2 are arithmetic expressions, which may be constants,
variables or combination of them.
• When arithmetic expressions are used on either side of a relational
operator, the arithmetic expressions will be evaluated first and then the
results are compared.
• That is arithmetic operators have a higher priority over relational
operators.
• Relational expressions are used in decision statements such as if and while
to decide the course of action of a running program.
• Logical operators
• In addition to the relational operators, C has the following three logical
operators:
logical AND (&&), logical OR ( || ) and logical NOT (!)
• The logical operators && and || are used when a test is to be done with more
than one condition and make decisions.
• An example is :
a>b && x == 10
• An expression of this kind, which combines two or more relational
expressions, is termed as a logical expression or a compound relational
expression.
• Like relational expression, logical expression also yields a value of one or zero.
exp1 exp2 exp1&&exp2 exp1||exp2
T T T T
T F F T
F T F T
F F F F

exp !exp
T F
F T
Operator Description Example a=20,b=10 Output
&& logical AND (a>b)&&(a<c) (10>20)&&(10<30) 0
|| logical OR (a>b)||(a<=c) (10>20)||(10<30) 1
! logical NOT !(a>b) !(10>20) 1
• Assignment operator
• Assignment operator are used to assign the result of an expression to a variable.
• We already have seen the usual assignment operator, ‘=‘.
• In addition, C has a set of shorthand assignment operators of the form:
V op= exp;
• Where v is a variable, exp is an expression and op is a C binary arithmetic operator.
• The operator op= is known as the shorthand assignment operator.
• The assignment statement
V op= exp;
Is equivalent to
V = V op exp;
• The use of shorthand assignment operators has three advantages:
• What appears on the left-hand side need not be replaced and therefore it
becomes easier to write.
• The statement is more concise and easier to read
• The statement is more efficient
• Increment and decrement operators (Unary operator)
• Increment operator (++)
• This operator increments the value of a variable by 1
• The two types include −
pre increment
post increment
• If the increment operator is placed before the operand, then it is pre-
increment. Later on, the value is first incremented and next operation is
performed on it.
• For example,
z = ++a; is equivalent to a= a+1 then z =a
• If we place the increment operator after the operand, then it is post
increment and the value is incremented after the operation is
performed.
• For example,
z = a++; is equivalent to z=a then a= a+1
What is the output of the following program:
#include <stdio.h>
int main() {
float a = 5, b=6;
int x = ++a - b +10;
printf("%d\n%f",x,a);
return 0;
}
• Decrement operator:
• It is used to decrement the values of a variable by 1.
• The two types are −
• pre decrement
• post decrement
• If the decrement operator is placed before the operand, then it is called pre
decrement. Here, the value is first decremented and then, operation is
performed on it.
• For example,
z = - - a; is equivalent to a= a-1 then z=a
• If the decrement operator is placed after the operand, then it is called
post decrement. Here, the value is decremented after the operation is
performed.
• For example,
z = a--; is equivalent to z=a then a= a-1
• Conditional operator
• A ternary operator pair “?:” is available in C to construct conditional
expressions of the form
Exp1?exp2:exp3
Where exp1, exp2 and exp3 are expressions.
• The operator “?:” works as follows: exp1 is evaluated first. If it is non zero
(true), then the expression exp2 is evaluated and becomes the value of the
expression.
• If exp1 is false, exp3 is evaluated and its value becomes the value of the
expression.
• Note that only one of the expressions (either exp2 or exp3) is evaluated.
If exp1 is true, exp2 is evaluated. Otherwise, exp3 is evaluated. Or in
the form of if-else.
if (exp1)
exp2;
else
exp3;
• Bit wise operator
• C has a distinction of supporting special operators known as bitwise operators
for manipulation of data at bit level.
• These operators are used for testing the bits, or shifting them right or left.
• Bitwise operators may not be applied to float or double.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left Shift
>> Right shift
~ One's Complement
Bitwise AND Bitwise OR
a b a&b a b a|b
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 1

What is the output of this program?


Bitwise XOR #include<stdio.h>
a b a^b main ( ){
0 0 0 int a= 12, b = 10;
0 1 1 printf (" %d", a&b);
1 0 1 printf (" %d", a| b);
1 1 0 printf (" %d", a ^ b);
}
• Left Shift
• If the value is left shifted one time, then its value gets doubled.
• For example, a = 10, then a<<1 = 20
• Right shift
• If the value of a variable is right shifted one time, then its value becomes half
the original value.
• For example, a = 10, then a>>1 = 5
• Ones complement
• It converts all ones to zeros and zeros to ones.
• For example, a = 5, then ~a=2 [only if 4 bits are considered].
• Special Operator
• C supports some special operators of interest such as comma operator, sizeof
operator, pointer operators (& and *) and member selection operators
(. and ->)
• Comma operator
• The comma operator can be used to link the related expressions together.
• A comma-linked list of expressions are evaluated left to right and the value of right-most
expression is the value combined expression.
• For example,
v = (x=10,y=5,x+y)
First assigns the value of 10 to x, then assigns 5 to y, and finally assigns 15(i.e. 10+5) to v.
• t= x, x= y, y= t;
• The sizeof operator
• The sizeof is a compile time operator and, when used with an operand, it
returns the number of bytes the operand occupies.
• The operand may be a variable, a constant or a data type qualifier.
• Examples:
m = sizeof(sum);
n = sizeof(long int);
k = sizeof(235L);
Q. What is the output of the program?
#include<stdio.h>
int main()
{
int a,b,c,d;
a =15;
b= 10;
c= ++a – b;
printf(“a=%d b=%d c =%d\n”,a,b,c);
d = b++ +a;
printf(“a=%d b=%d d =%d\n”,a,b,d);
printf(“a/b=%f\n”, a/b);
printf(“a%%b = %d”,a%b);
printf(“a *= b =%d”,a*=b);
printf(“%d\n”,(c>d)?1:0);
printf(“%d\n”,(c<d)?1:0);
return 0;
}
Evaluation of Expressions
• Expressions are evaluated using an assignment statement of the form:
variable = expression;
• When the statement is encountered, the expression is evaluated first
and the result then replaces the previous value of the variable on the
left handside.
• All variables used in the expression must be assigned values before
evaluation is attempted.
• Examples of evaluation statements are:
x = a * b – c;
y = b / c * a;
z = a – b / c + d;
• The blank space around an operator is optional and adds only to
improve readability.
• When these statements are used in a program, the variables a,b,c and
d must be defined before they are used in the expression.
Precedence of Arithmetic Operators
• An arithmetic expression without parentheses will be evaluated from
left to right using rules of precedence of operators.
• There are two distinct priority levels of arithmetic operators in C:
• High priority: * / %
• Low priority: + -
• Try out example for x = 9 – 12 /3 + 3 * 2 – 1
• Rules for Evaluation of Expression:
• First, parenthesized sub expression from left to right are evaluated
• If parentheses are nested, the evaluation begins with innermost sub
expression
• The precedence rule is applied in determining the order of application of
operators in evaluating sub expressions
• The associativity rule is applied when two or more operators of the same
precedence level appear in a sub expression
• Arithmetic expressions are evaluated from left to right using the rules of
precedence.
• When parentheses are used, the expressions within parentheses assume
highest priority.

Solve for 9 – (12/3) + 3*2 - 1


Type Conversion
• Implicit conversion
• C permits mixing of constants and variables of different datatypes in an
expression.
• C automatically converts any intermediate values to the proper type so that
the expression can be evaluated without losing any significance.
• The automatic conversion is called implicit conversion.
• During evaluation it adheres to very strict rules of type conversion.
• If operands are of different types, the ‘lower’ type is automatically converted
to ‘higher’ type before the operation proceeds.
• The result is of higher type.
int i,x;
float f;
double d;
long l;
x=l/i+i*f-d
• Following are the rules for the implicit type conversion in C.
• First, all char and short are converted to int data type.
• Then, If any of the operand in the expression is long double then others will be
converted to long double and we will get the result in long double.
• Else, if any of the operand is double then other will be converted into double and the
result will be in double.
• Else, if any of the operand is float then other will be converted into float and the result
will be in float.
• Else, if any of the operand is unsigned long int then others will be converted into
unsigned long int and we will get the result in unsigned long int.
• Else, if any of the operand is long int and another is in unsigned int then,
• If unsigned int can be converted to long int then it will be converted into long int and
the result will be in long int.
• Else, both will be converted into unsigned long int and the result will be in unsigned
long int.
• Else, if any of the operand is long int then other will be converted to long int and we
will get the result in long int.
• Else, if any of the operand is unsigned int then other will be converted into unsigned
int and the result will be in unsigned int.
• Explicit Conversion
• There are instances when we want to force a type conversion in a way that is
different from the automatic conversion.
• Consider, for example, the calculation of ratio of females to males in a town:
ratio = female_number/male_number
• Since female_number and male_number are declared as integers in the
program, the decimal part of the result of the division would be lost and ratio
would represent a wrong figure.
• This problem can be solved by converting locally one of the variables to the
floating point as shown below:
ratio = (float)female_number/male_number
• The operator (float) converts the female_number to floating point for
the purpose of the evaluation.
• Then using the rule of automatic conversion, the division is
performed in floating point mode, thus retaining the fractional part of
result.
• Note that in no way does the operator (float) affect the value of the
variable female_number.
• Also, the type of female_number remains as int in the other parts of
the program.
• The process of such a local conversion is known as explicit conversion
or casting a value.
• The general form:
(type-name)expression
Examples Action
X = (int) 7.5 7.5 is converted to integer by truncation
A = (int) 21.3 / (int) 4.5 Evaluated as 21/4 and the result would
be 5
B = (double)sum/n Division is done in floating point mode
Y = (int)(a+b) The result of a+b is converted to int
Z = (int) a + b A is converted to integer and then added
to b
P = cos((double)x) Converts x to double before using it
Category Operator Associativity
Postfix () [] Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

You might also like