Lesson5-Operators and Precedence
Lesson5-Operators and Precedence
-III 4
Chapter Outline
“First, master the fundamentals.”
–Larry Bird
Introduction.
Types of operators
Assignment operator
Binary arithmetic operators.
Unary arithmetic operators.
Relational operators.
“I long to accomplish great and noble task, but
Logical operators.
it is my chief duty to accomplish small tasks as
if they were great and noble.” Conditional operator
–Helen Keller
Bitwise operators.
Special operators.
Operator’s precedence and
associativity.
Evaluating an expression.
“Success is neither magical nor mysterious. Success Type conversion in an
is the natural consequence of consistently applying expression.
the basic fundamentals.”
–Jim Rohn Conclusion.
Types of operators
Assignment operator
Binary arithmetic
operators.
Unary arithmetic
operators.
Relational operators.
Logical operators.
Conditional operator
Bitwise operators.
Special operators.
Operator’s precedence and
associativity.
Evaluating an expression.
Type conversion in an
expression.
Conclusion.
5.1. Introduction
Operator: Operator is a special character (or symbol) that performs an operation using operands.
Operand: Operand is a variable or constant that acts as input for an operation to be performed.
Expression: Expression is a collection of operators and operands that, when evaluated, returns a value.
Ex: a+b is an expression in which the operator is + and the operands are a and b.
Unary operator: Unary operator is an operator that performs operation using only one operand at a
time.
e.g., ++ (increment) is a unary operator.
Binary operator: Binary operator is an operator that performs operation using two operands at a time.
e.g., > (greater than) is a binary operator.
Ternary operator: Ternary operator is an operator that performs operation using three operands at a
time.
e.g., ?:(Conditional operator) is ternary operator.
Operand_1=Operand_2;
Here, Operand_1 (also called as LValue) can be a variable or constant. Operand_2 (also called as RValue)
can also be a variable or constant or an expression.
Note:
1. The operator % does not work on the operands of data types: float or double or long double.
2. An unusual aspect of programming in C is the arithmetic which can be done with characters.
Consider the following:
char ch1,ch2;
ch1=’a’; /*assign ‘a’ to ch1*/
ch2=ch1+1; /*assign ‘b’ to ch2*/
The second assignment increases the ASCII (American Standard Code for Information Interchange) value
for the given character, a numeric value, by 1 and sets the result to ch2. Thus, ch2 contains ‘b’.
3. x%y is always equals to (x-(x/y)*y).
4. The second operand of operators % and / must be non-zero.
Program #3
Write a program to convert an alphabet from lowercase to uppercase
/*program to convert the lowercase to uppercase*/
#include<stdio.h>
main()
{
char ch;
printf(“\n Enter any lowercase alphabet:\n”);
scanf(“%c”,&ch); /* or ch=getchar();*/
ch=ch-32;
printf(“\n Uppercase alphabet:%c”,ch);
}
Output:
Enter any lowercase alphabet:
m
Uppercase alphabet:M
O 2)#include<stdio.h>
}
5)#include<stdio.h>
}
8)#include<stdio.h>
U main()
{
float a=1.5;
main()
{
printf(“%d”,4%3);
main()
{
int x;
T
int b=3; printf(“%d”,4%-3); x=4%5+6%5;
a=b/2+b*8/b-b+a/3; printf(“%d”,-4%3); printf(“x=%d”,x);
printf(“a=%f”,a); printf(“%d”,-4%-3); }
} }
P 3)#include<stdio.h>
6)#include<stdio.h> 9)#include<stdio.h>
main() main()
U main()
{
int x;
{
float a=5,b=2;
{
int x;
x=3*4%5;
int c;
T
x=-3*-4%-6/-5; c=a%b; printf(“x=%d”,x);
printf(“x=%d”,x); printf(“%d”,c); }
} }
7)#include<stdio.h>
9)#include<stdio.h>main() 8)#include<stdio.h>
main() { main()
{ float a=4; {
int q=2,d=3,st; int i=2; float a;
st=q*d/4-12/12+12/3*16/d; printf(“%f%d”,i/a,i/a); a=4/2;
printf(“st=%d”,st); printf(“%d%f”,i/a,i/a); printf(“%f%f”,a,4/2);
} } }
5.2.3. Unary arithmetic operators
Unary Arithmetic operators perform the arithmetic operations such as increment & decrement and change of
sign on only one operand. There are 4 unary arithmetic operators:
Operator Operation
Unary + (Positive) Keeps the sign of value unchanged.
Unary - (Negative) Changes the sign of value.
++ (Increment) Adds 1 to value of operand and assigns the result to that operand only.
-- (Decrement) Subtracts 1 from the value of operand and assigns the result to that operand
only.
Operand_1 Unary_arithmetic_operator
(or)
Unary_arithmetic_operator Operand_1
Both sign operators should be preceded by the operand where as the increment and decrement operators
can be preceded or followed by the operand.
Ex: int a=10;
1) +a /*keeps the sign of 10 as positive only*/
2) –a /* changes the sign of 10 to negative*/
3) ++a or a++ /* equivalent to a=a+1; hence, a holds 11*/
4) –-a or a-- /* equivalent to a=a-1; hence, a holds 9*/
Program #4
Write a program to demonstrate positive and negative signs
/*program to demonstrate positive and negative signs*/
#include<stdio.h>
main()
{
int num;
printf(“\n Enter any number:”);
scanf(“%d”,&num);
printf(“\n Positive number=%d”,+num);
printf(“\n Negative number=%d”,-num);
printf(“\n Positive number=%d”,+(+num));
printf(“\n Negative number=%d”,+(-num));
printf(“\n Positive number=%d”,-(-num));
printf(“\n Negative number=%d”,-(+num));
}
Output:
Enter any number: 123
Positive number=123
Negative number=-123
Positive number=123
Negative number=-123
Positive number=123
Negative number=-123
Few words about increment and decrement operators:
If ++ is used before the operand, then this increment operator is called as pre-increment operator. If +
+ is used after the operand, then this increment operator is called as post-increment operator. The
same treatment will be given to the --.
The increment / decrement operator works as a simple increment / decrement by one, if it is not
used as a part of an expression. In that case, there is no difference between operations of pre or post
increment or decrement operators.
However, when these operators are used as a part of an expression then the difference can be
noticed:
The pre-increment operator first increments the value of operand and then returns that
incremented value.
The post-increment operator first returns the existing value of operand and then increments the
value of the operand.
The pre-decrement operator first decrements the value of operand and then returns that
decremented value.
The post-decrement operator first returns the existing value of operand and then decrements the
value of the operand.
O
main() main()
2)#include<stdio.h> { {
main() int x=3,z; int x=3,z;
{ z=x--- -1; z=x++ + ++x;
U int x=3,z;
z=x++ +10;
printf(“x=%d z=%d”,x,z); printf(“x=%d z=
%d”,x,z);
printf(“x=%d z=%d”,x,z); } }
T }
3)#include<stdio.h> 6)#include<stdio.h>
main()
9)#include<stdio.h>
main()
main()
P {
int x=3,z;
{
int x=3,z;
z=x----1;
{
int x=3,z;
z=x/++x;
z=++x +10;
T 10)#include<stdio.h>
main()
11)#include<stdio.h>
main()
12)#include<stdio.h>
main()
{ { {
int i=3,j; int x=4,y=3,z; int a,b;
j=++i*++i*++i; z=x-- -y; a=-3 - -3;
printf(“i=%d j=%d”,i,j); printf(“x=%dy=%dz= b=-3 - -(-3);
%d”,x,y,z); printf(“%d%d”,a,b);
} } }
Operator Operation
&& (Logical AND) Performs Logical AND operation on two operands.
|| (Logical OR) Performs Logical inclusive OR operation on two operands.
! (Logical NOT) Reverses the value of operand.
The logical operators are used to form logical expressions as shown below:
1) Logical AND expression:
Where Expression_1 and Expression_2 are any expression those return either true or false.
When logical AND operator is encountered, first Expression_1 is tested. It returns either true or false.
Secondly, the expression_2 is tested. It returns either true or false. Then both of these expressions’ values are
combined to give the value of logical expression as given below:
Expression_1 Expression_2 Expression_1 && Expression_2
1 1 1
1 0 0
0 1 0
0 0 0
Ex: int a=10,b=30,c;
c=((a>b)&&(a!=b)); Ans: c=1
Note: If the left operand yields false value, the right operand is not evaluated by a compiler in a logical
expression using &&.
2) Logical OR expression:
Expression_1 || Expression_2
Where Expression_1 and Expression_2 are any expression those return either true or false.
When logical AND operator is encountered, first Expression_1 is tested. It returns either true or false.
Secondly, the expression_2 is tested. It returns either true or false. Then both of these expressions’ values are
combined to give the value of logical expression as given below:
Expression_1 Expression_2 Expression_1 || Expression_2
1 1 1
1 0 1
0 1 1
0 0 0
Ex: int a=10,b=30,c;
c=((a>b)||(a!=b)); Ans: c=1
Note: If the left operand yields true value, the right operand is not evaluated by a compiler in a logical
expression using ||.
3) Logical NOT expression:
!(Expression_1)
O {
int x,y,z;
x=y=z=1;
{
int x,y,z;
x=y=z=-1;
{
int a=30,b=40,x;
x=(a!=10)&&(b=50);
U
z=++x&&++y&&++z; z=++x&&++y&&++z; printf(“x=%d”,x);
printf(“%d %d %d”,x,y,z); printf(“%d %d %d”,x,y,z); }
} }
T 3)#include<stdio.h>
main()
6)#include<stdio.h>
main()
9)#include<stdio.h>
main()
{
P
{ {
int a=100,b=200,c;
int x,y,z; int x,y,z;
c=(a==100||b>200);
x=y=z=1; x=y=z=-1;
printf(“c=%d”,c);
z=++x&&++y||++z; z=++x&&++y||++z;
U printf(“%d %d %d”,x,y,z);
}
printf(“%d %d %d”,x,y,z);
}
}
T 10)#include<stdio.h>
main()
11)#include<stdio.h>
main()
12)#include<stdio.h>
main()
{ { {
int x=11,y=6,z; int x=10,y=-20; int x=0,y=1;
z=x==5||y!=4; x=!x; y=!x;
printf(“z=%d”,z); y=!y; x=!y;
} printf(“%d %d”,x,y); printf(“%d %d”,x,y);
} }
5.2.6. Conditional operator
The conditional operator consists of two symbols: the question mark (?) and the colon (:). This is the only
operator in C that acts on three operands at a time. Hence, this operator is also called as ternary operator
or trinary operator. This operator acts in the same way as the if…else statement acts. Conditional
operator can be used as follows:
False True
Condition
Expression_2 Expression_1
Next_statement
Program #4
Write a program to find biggest of three numbers
/*program to find biggest of three numbers*/
#include<stdio.h>
main()
{
int num1,num2,num3,big;
printf(“\n Enter any three numbers:”);
scanf(“%d%d%d”,&num1,&num2,&num3);
big=((num1>num2)&&(num1>num3)?num1:num2>num3?num2:num3;
printf(“\n Biggest of three numbers=%d”,big);
}
Output:
Enter any three numbers: 190
452
43
Biggest of three numbers=452
1)#include<stdio.h> 4)#include<stdio.h>
main() main()
{ {
int x=3,y=4,z=4; int k=12,n=30;
printf(“ans=%d”,z>=y&&y>=x?1:0); k=(k>5&&n=4?100:200);
OBSERVABLE } printf(“k=%d”,k);
}
O 2)#include<stdio.h>
main() 5)#include<stdio.h>
U {
int x=3,y=4,z=4;
main()
{
printf(“ans=%d”,z>=y>=x?1:0); int c=0,d=5,e=10,a;
T } a=c>1?d>1||e>1?100:200:300;
printf(“a=%d”,a);
}
P 3)#include<stdio.h>
main()
6)#include<stdio.h>
{
main()
U int i=-4,j,num=10;
j=i%-3;
j=(j?0:num*num);
{
int a=10,b=10;
printf(“ans=%d”,a>b?a*a:b/b);
T
printf(“j=%d”,j);
}
}
Bitwise operators perform operations on bits of data. These operators are used for testing, complementing
or shifting bits to the right or left. Usually, bitwise operators are not useful in cases of float and double.
There are six bitwise operators as shown below:
Operator Operation
& (Bitwise AND) Returns 1 if both corresponding bits are 1; otherwise 0.
| (Bitwise inclusive OR) Returns 0 if both corresponding bits are 0; otherwise 1.
^(Bitwise exclusive OR) Returns 0 if both corresponding bits are 0 or 1; otherwise 1.
~ (One’s complement) Returns 1, if bit is 0 and returns 0, if bit is 1.
<< (Left shift) Shifts least significant bit by specified number of times.
>> (Right shift) Shifts most significant bit by specified number of times.
All these operators are binary operators except one’s complement operator. One’s complement operator is
a unary operator.
Bitwise AND (&):
The operator & performs a bitwise AND between two operands. It compares each bit of the left operand
with the corresponding bit of the right operand. For each bit, the result is 1, if both the compared bits are
1; otherwise, the result is 0 as shown below:
Interview question #1
What is masking?
Masking is an operation in which the desired bits of a binary number or bit pattern are set to zero. The
operator & (Bitwise AND) is very useful for this purpose. To mask particular bits in a binary number, do
the following:
1. Create a new number that has binary pattern with 0s in the positions that you want to mask and
1s in other positions.
2. Perform bitwise AND operation between the number that is to be masked and created number.
Constant >> n
(or)
variable >>n
Constant << n
(or)
variable <<n
~operand1
Program #5
Write a program to convert an uppercase alphabet to lowercase alphabet
/*program to convert an uppercase alphabet to lowercase alphabet*/
#include<stdio.h>
int main()
{
char alpha;
printf(“\n Enter any uppercase alphabet:”);
scanf(“\n%c”,&alpha);
printf(“\n Lower case alphabet=%c”, alpha | 32);
return 0;
}
Output:
Enter any uppercase alphabet:
A
Lower case alphabet=a
Program #6
Write a program to swap two integers with out using temporary variable
/*program to swap two integers without using temporary variable*/
#include<stdio.h>
int main()
{
int a,b;
printf(“\n Enter any two numbers:”);
scanf(“%d%d”,&a,&b);
printf(“\n Before swap a=%d\tb=%d”,a,b);
a=a^b;
b=a^b;
a=a^b;
printf(“\n After swap a=%d\tb=%d”,a,b);
return 0;
}
Output:
Enter any two numbers: 10
20
Before swap a=10 b=20
After swap a=20 b=10
5.2.8. Special operators
1. sizeof operator.
2. comma operator.
3. short-hand operators.
4. Referencing and dereferencing operators.
sizeof operator: It is an unary operator. It returns the number of bytes occupied by the operand in
memory. The operand may be a variable, a constant, an expression or simply a datatype.
Ex: printf(“%d”,sizeof(10)); /*prints 2 or 4*/
printf(“%d”,sizeof(int)); /*prints 2 or 4*/
int x=30; float y=45.355;
printf(“%d”,sizeof(y)); /*prints 4*/
printf(“%d”,sizeof(x+y)); /*prints 4*/
Comma Operator: A comma operator can be used as a separator or a terminator in the following
statements:
int a,b,c;
c=a,a=b,b=c;
This operator can also be used to link related expressions together. A comma-linked list of expressions
is evaluated from left to right and the value of right-most expression is the value of combined
expression.
Ex: value=(x=10,y=20,x+y); ans: value=30
Short-hand Operators: These operators are formed by combining both binary arithmetic operators
and bitwise operators with assignment operator. Hence, these are also called as compound assignment
operators.
The short-hand operators include: +=, -=, *=, /=, %=
&=, |=, ^=, <<=, >>=.
All of these operators are binary operators. So, these operands should act on two operands at a time.
O a) y=(int) (x+0.5);
b) y=int (x+0.5);
U c) y=(int )x+0.5;
d) y=(int)((int)x+0.5)
T 1)#include<stdio.h>
main()
{
P printf(“%d %d %d”,sizeof(3.14f),sizeof(3.14),sizeof(3.14l));
}
U 2)#include<stdio.h>
main()
T
{
printf(“%d”,sizeof(4)/sizeof(2.0));
printf(“%d”,sizeof(2.0)/sizeof(4));
}
1 2 () [] . -> Left-to-Right
2 1 ! ~ ++ -- + - * & Right-to-Left
(type) sizeof
3 2 * / % Left-to-Right
4 2 + - Left-to-Right
7 2 == != Left-to-Right
8 2 & Left-to-Right
9 2 ^ Left-to-Right
10 2 | Left-to-Right
11 2 && Left-to-Right
12 2 || Left-to-Right
13 3 ? : Left-to-Right
14 2 = *= /= %= += -= Right-to-Left
&= |= ^= <<= >>=
15 2 , Left-to-Right
long double
Broadening doubleNarrowing
short
conversion int
unsigned
char
long
unsigned
int
int long int
float conversion
This type conversion can be done either implicitly or explicitly.
Implicit type conversion: C permits mixing of constants and variables of different data types in an
expression. C automatically converts any intermediate values to the proper type so that expression can be
evaluated with out loosing any significance. This automatic conversion is known as implicit type
conversion.
During evaluation, the lower type is automatically converted to the higher type, according to strict
rules of type conversion. The rules for this type conversion are as follows:
1. If one of the operands is a long double, then the other is converted a long double.
2. Otherwise, if one of the operands is a double, then the other is converted to a double.
3. Otherwise, if one of the operands is a float, then the other is converted to a float.
4. Otherwise, if one of the operands is an unsigned long, then the other is converted to an unsigned
long.
5. Otherwise, if one of the operands is a long, then the other is converted to a long.
6. Otherwise, if one of the operands is unsigned int, the other is converted to unsigned int.
7. Otherwise, both operands are converted to int values.
1)#include<stdio.h>
main()
{
printf(“%d %d %d”,72,072,0x72);
OBSERVABLE }
O
U
T 2)#include<stdio.h>
main()
P
{
U printf(“%d %o %x”,72,72,72);
T }
Explicit type conversion: When we want to do type conversion forcefully, then we use cast operator.
Cast operator is used to convert value of an operand from one type to another explicitly by the user. This
explicit type conversion is also called as casting or coercion.
The usage of cast operator is as follows:
(type_name) expression
Here, type_name is any standard data type. The expression may be a constant, variable or an expression.
As this operator works on only one operand at a time, this is a unary operator.
5.6. Conclusion
C supports arithmetic, relational and logical operators like other programming languages. It supports
increment and decrement operators for faster execution. Bitwise operators are supported in C, which are
not available in other languages. In addition to simple assignments, C also provides compound
assignments or short-hand assignments.
Expressions are formulated with the help of operators and operands. These are evaluated to get
the desired result. These are evaluated according to the precedence levels of the operators and their
associativity. In evaluating mixed-type expressions, implicit conversion rules are followed. Explicit type
conversions are possible with coercion or type casting.