UNIT 2ND OPERATORS & EXPRESSIONS
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C language is rich in built-in
operators and provides the following types of operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Increment and decrement operators
• Conditional operators
• Mixed mode operators
• Mathematical functions
C operators:
C has a rich set of operators. They may operate on a single operand or two
operands. They are used to perform basic arithmetic operations, comparisons,
manipulation of bits and so on.
C Operators:
1. Unary operators
2. Binary operators
3. Ternery operators
Unary operators:
An operator that acts upon only one operand is known as a unary operator.
There are 3 types of unary operators are there
1. Unary minus
2. Logical NOT operator
3. Bitwise complementation
Unary minus:
Any operand associated with unary minus operator gets its value changed to
negative.
Example: a=3, b=4
C=a+(-b)
=3+(-4)
=-1
Or -2, -5.5 etc
Binary operators;
Operators act upon two operands that is called as binary operands.
Types of binary operands;
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Bitwise operators
Arithmetic operators;
These are used to perform mathematical calculations like
addition, subtraction, multiplication, division and modulus.
Following table shows all the arithmetic operators supported by C language.
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
+ Adds two operands A + B will give
30
- Subtracts second operand from the first A – B will give -
10
* Multiplies both operands A * B will give
200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer B % A will give
division 0
++ Increments operator increases integer value by one A++ will give 11
-- Decrements operator decreases integer value by A–will give 9
one
Example program:
#include <stdio.h>
void main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
}
Evaluation of arithmetic expressions;
Expressions: An expression in C is a combination of operands and operators –
it computes a single value stored in a variable. The operator denotes the action or
operation to be performed. The operands are the items to which we apply the
operation.
Rules for evaluation of arithmetic expressions
1. First evaluate within bracket
2. Next evaluate unary minus
3. * and / operator are evaluated
4. + and – are evaluated next
Precedence table:
Operations Operator Precedence Associativity
Addition + 2 L TO R
Subtraction - 2 L TO R
Multiplication * 1 L TO R
Division / 1 L TO R
Modulus % 1 L TO R
Example: Evaluate the following arithmetic expression 2*((i/3)+4*(j-2))
Given i=6 j=4
Solution: 2*((i/3)+4*(j-2))
2*((6/3)+4*(4-2))
2*(2+4*(4-2))
2*(2+4*2)
2*(2+8)
2*10
20
Relational Operators. A relational operator checks the relationship
between two operands. If the relation is true, it returns 1; if the relation
is false, it returns value [Link] may be variables, constants or
expressions. Relational operators are used in decision making and
loops.
Operator Meaning Example Return value
< is less than 2<9 1
<= is less than or equal to 2<=2 1
> is greater than 2>9 0
>= is greater than or equal to 3>=2 1
== is equal to 2==3 0
!= is not equal to 2!=2 0
// C Program to demonstrate the working of relational operators
#include <stdio.h>
int main()
int a = 8, b = 5;
if(a>b)
printf("a is big);
}
Precedence table:
Operator Meaning precedence associativity
< is less than 1 L TO R
<= is less than or equal to 1 L TO R
> is greater than 1 L TO R
>= is greater than or equal to 1 L TO R
== is equal to 2 L TO R
!= is not equal to 2 L TO R
Logical Operators.
These operators are used to combine the results of two or more
conditions. An expression containing logical operator returns either 0
or 1 depending upon whether expression results true or false. Logical
operators are commonly used in decision making in C programming.
Operator Meaning precedence associativity
&& Logical 2 L TO R
AND
|| Logical OR 3 L TO R
! Logical NOT 1 L TO R
Logical AND : If any one condition false the complete condition becomes false.
Truth Table
Op1 Op2 Op1 &&
Op2
true true true
true false false
false true false
false false false
Logical OR : If any one condition true the complete condition becomes true.
Truth Table
Op1 Op2 Op1 // Op2
true true true
true false true
false true true
false false false
Logical Not : This operator reverses the value of the expression it
operates on i.e, it makes a true expression false and false expression
true.
Op1 Op1 !
true False
false true
Evaluation of logical expressions;
Example: evaluate the following logical expression a&&b ||c&&(!b)
Value of a=2, b=4 and c=3
Solution:
a&&b ||c&&(!b)
2&&4 ||3&&(!4)
2&&4 ||3&&(0)
2&&4 ||3&&0
1||3&&0
1||0
1
C program to illustrate logical operators:
#include<stdio.h>
Void main()
{
Int a=4,b=3,c;
c=a&&b;
b=a||b||c;
a=a&&b||c;
printf(“%d%d%d”,a,b,c);
}
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Bitwise
operators are used in bit level programming. These operators can operate
upon int and char but not on float and double.
Showbits( ) function can be used to display the binary representation of
any integer or character value.
Operator Symbol name meaning
& Ampersand Bitwise AND
| Pipeline Bitwise OR
^ Caret Bitwise XOR
~ Tilde 1s complement
<< Double less than Left shift of bits
>> Double greater than Right shift of bits
Example of bitwise AND
a =00000100
b =00000011
a&b =00000000
Example of bitwise OR
a =00000100
b =00000011
a&b =00000111
Example of bitwise XOR
a =00000100
b =00000111
a&b =00000011
Bitwise complement:
It is used to 1s complement of binary sequence.
Example: let a=10
b=~a
binary number of 10=1010
b=~(1010)
=0101 which is 1s complement
Bitwise left shift:
Shifting bit one position to left
Example: a=101010
Before left shifting value is 1 0 1 0 1 0
After left shift value is 0 1 0 1 0 1
Bitwise right shift:
Shifting bit one position to right
Example: a=101011
Before right shifting value is 1 0 1 0 1 1
After right shift value is 1 1 0 1 0 1
Increment and Decrement Operators /Unary Operators:
Unary operators are having higher priority than the other operators. Unary
operators, meaning they only operate on a single operand. Increment Operator in
C Programming
1. Increment operator is used to increment the current value of
variable by adding integer 1.
2. Increment operator can be applied to only variables.
3. Increment operator is denoted by ++.
We have two types of increment operator i.e Pre-Increment
and Post-Increment Operator
. Pre-Increment
Pre-increment operator is used to increment the value of variable
before using in the expression. In
the Pre-Increment value is first incremented and then used inside the
expression.
b = ++y;
In this example suppose the value of variable „y‟ is 5 then
value of variable „b‟ will be 6 because the value of „y‟ gets
modified before using it in a expression.
Post-Increment
Post-increment operator is used to increment the value of
variable as soon as after executing expression completely in
which post increment is used. In the Post-Increment value is
first used in a expression and then incremented.
b = x++;
In this example suppose the value of variable „x‟ is 5 then
value of variable „b‟ will be 5 because old value of „x‟ is
used.
Operator Meaning
++x Pre increment
- -x Pre decrement
x++ Post increment
x-- Post decrement
Where
1 : ++x : Pre increment, first increment and then do the operation.
2 : - -x : Pre decrement, first decrements and then do the operation.
3 : x++ : Post increment, first do the operation and then increment.
4 : x- - : Post decrement, first do the operation and then decrement.
#include <stdio.h>
int main()
{
int c=2,d=2;
printf(“%d\n”,c++); //this statement displays 2 then, only c incremented by 1 to
3.
Printf(“%d”,++c); //this statement increments 1 to c then, only c is displayed.
Return 0;
}
Assignment Operators:
In C programs, values for the variables are assigned using assignment
operators.
There are following assignment operators supported by C language:
Operator Description Example
= Simple assignment operator, Assigns values from right C = A + B will assign value
side operands to left side operand of A + B into C
+= Add AND assignment operator, It adds right operand to C += A is equivalent to C =
the left operand and assign the result to left operand C+A
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C = C
operand from the left operand and assign the result to –A
left operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C = C
operand with the left operand and assign the result to *A
left operand
/= Divide AND assignment operator, It divides left C /= A is
operand with the right operand and assign the result to equivalent to C = C / A
left operand
%= Modulus AND assignment operator, It takes modulus C %= A is
using two operands and assign the result to left operand equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C <<
2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >>
2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
Conditional Operator/ Ternary operator:
conditional operator checks the condition and executes the statement
depending of the condition. A conditional operator is a ternary
operator, that is, it works on 3 operands.
Conditional operator consist of two symbols.
Syntax: expression ? value1 :value2
Example: c=a<b?a:b
#include<stdio.h>
Void main()
int x=4, y ;
y = ( x<5 ? 4 :5 ) ;
printf(“y=%d”,y);
}
Special Operators
1) Comma Operator :The comma operator is used to separate the statement
elements such as variables, constants or expressions, and this operator is used to
link the related expressions together, such expressions can be evaluated from left to
right and the value of right most expressions is the value of combined expressions
1 Ex : val(a=3, b=9, c=77, a+c)
2 First signs the value 3 to a, then assigns 9 to b, then
assigns 77 to c, and finaly80(3+77) to value.
Sizeof Operator : The sizeof() is a unary operator, that returns the
length in bytes o the specified variable, and it is very useful to find the
bytes occupied by the specified variable in the memory.
Syntax : sizeof(variable-name);s
int a;
Ex : sizeof(a); //OUTPUT - 2bytes
Example program;
#include<stdio.h>
Void main()
Int x=9; float y=9.9; char ch=’c’;
Printf(“size of x=%d”, sizeof(x));
Printf(“size of y=%d”,sizeof(y));
Printf(“size of ch=%d”,sizeof(ch));
}
Operator Precedence and Associativity :
Every operator has a precedence value. An expression containing
more than one oerator is known as complex expression. Complex
expressions are executed according to precedence of operators.
Associativity specifies the order in which the operators are
evaluated with the same precedence in a complex expression.
Associativity is of two ways, i.e left to ringht and right to left. Left
to right associativity evaluates an expression starting from left and
moving towards right. Right to left associativity proceds from right
to left.
Operator Description Precedence Associativity
() Function call 1 L-R (left to right)
[] Square brackets.
+ Unary plus 2 R-L (right to left)
- Unary minus
++ Increment
-- Decrement
! Not operator
~ Complement
* Pointer operator
& Address operator
sizeof Sizeof operator
* Multiplication 3 L-R (left to right)
/ Division
% Modulo division
+ Addition 4 L-R (left to right)
- Subtraction
<< Left shift 5 L-R (left to right)
>> Right shift
< <= > >= Relational Operator 6 L-R (left to right)
== Equality 7 L-R (left to right)
!= Inequality
& Bitwise AND 8 L-R (left to right)
^ Bitwise XOR 9 L-R (left to right)
| Bitwise OR 10 L-R (left to right)
&& Logical AND 11 L-R (left to right)
|| Logical OR 12 L-R (left to right)
?: Conditional 13 R-L (right to left)
= *= /= %= += Assignment operator 14 R-L (right to left)
-= &= ^= <<=
>>=
, Comma operator 15 L-R (left to right)
Type Conversion/Type casting:
Type conversion is used to convert variable from one data type to
another data type, and after type casting complier treats the variable
as of new data type.
For example, if you want to store a 'long' value into a simple integer
then you can type cast 'long' to 'int'. You can convert the values
from one type to another explicitly using the cast operator. Type
conversions can be implicit which is performed by the compiler
automatically, or it can be specified explicitly through the use of the
cast operator.
Syntax:
(type_name) expression;
Without Type Casting:
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
With Type Casting:
1. float f=(float) 9/4;
2. printf("f : %f\n", f );//Output: 2.250000
Selection Statement/Conditional Statements/Decision Making Statements
A selection statement selects among a set of statements
depending on the value of a controlling expression. Or
Moving execution control from one place/line
to another line based on
condition Or
Conditional statements control the sequence of statement
execution, depending on the value of a integer expression
C‟ language supports two conditional statements.
1: if
2: switch.
Conditional control statements:
1. if statement
2. if else statement
3. nested if statement
4. switch statement
if statement.
The if statement controls conditional branching. The body of an if
statement is executed if the value of the expression is nonzero. Or if
statement is used to execute the code if condition is true. If the
expression/condition is evaluated to false (0), statements inside the
body of if is skipped from execution.
Syntax : if(condition/expression)
true statement;
}
statement-x;
If the condition/expression is true, then the true statement will be
executed otherwise the true statement block will be skipped and the
execution will jump to the statement-x. The „true statement‟ may be
a single statement or group of statement.
If there is only one statement in the if block, then the braces are
optional. But if there is more than one statement the braces are
compulsory
Flowchart
#include<stdio.h>
Void main()
{
Int a=15,b=20;
If(b>a)
{
Printf(“b is greater”);
}
}
If-else statement : The if-else statement is an extension of the simple if
statement. The general form is. The if...else statement executes some
code if the test expression is true (nonzero) and some other code if the
test expression is false (0).
Syntax : if (condition)
{
true statement;
}
else
{
false statement;
}
statement-x;
flowchart:
#include<stdio.h>
Void main()
{
int a=15,b=20;
if(b>a)
{
Printf(“b is greater”);
}
else
{
Printf(“\n a is greater”);
}
}
Nested if-else statement
When a series of decisions are involved, we may have to use more
than on if-else statement in nested form. If –else statements can also
be nested inside another if block or else block or both.
Syntax :
if (condition1)
{
if(condition2)
{
true statement 1
}
else
{
false statement 2
}
}
else
{
statement 3;
}
statement-x;
If the condition-1 is false, the statement-3 and statement-x will
be executed. Otherwise it continues to perform the second test. If
the condition-2 is true, the true statement-1 will be executed
otherwise the statement-2 will be executed and then the control is
transferred to the statement-x
Flowchart:
Example program to find largest of three numbers;
#include<stdio.h>
Void main()
{
Int a,b,c;
Printf(“\n enter value of a,b,c”);
Scanf(“%d%d%d”,&a,&b,&c);
If(a>b)
{
If(a>c)
Printf(“ a is larger”);
Else
Printf(“\n c is larger”);
}
Else
{
If(b>c)
Printf(“\n b is greater”);
Else
Printf(“\n c is greater”);
}
}
Else if ladder.
The if else-if statement is used to execute one code from multiple
conditions.
Syntax : if( condition-1)
{
statement-1;
}
else if(condition-2)
{
statement-2;
}
else if(condition-3)
{
statement-3;
}
else if(condition-n)
{
statement-n;
}
else
{
Default statement;
}
statement-x;
Flow chart:
Switch statement : when there are several options and we have to
choose only one option from the available ones, we can use switch
statement. Depending on the selected option, a particular task can be
performed. A task represents one or more statements.
Switch(expression)
{
Case label1: block1;
Break;
Case label2: block2;
Break;
Case label3: block3;
Break;
Case default: block;
Break;
}
The expression following the keyword switch in any „C‟ expression that must yield an
integer value. It must be ab integer constants like 1,2,3 .
The keyword case is followed by an integer or a character constant, eachconstant in
each must be different from all the other.
First the integer expression following the keyword switch is evaluated. The value it
gives is searched against the constant values that follw the case statements. When a
match is found, the program executes the statements following the case. If no match
is found with any of the case statements, then the statements follwing the default are
executed.
Rules for writing switch() statement.
1 : The expression in switch statement must be an integer value or a
character constant.
2 : No real numbers are used in an expression.
3 : The default is optional and can be placed anywhere, but usually
placed at end.
4 : The case keyword must terminate with colon ( : ).
5 : No two case constants are identical. 6 : The case labels must be constants.
flowchart:
Example program:
#include <stdio.h>
int main () {
/* local variable definition */
char grade = 'B';
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statment can be
used to repeat some part of the code for a particular condition. It can also be used
to break the multiple loops which can't be done by using a single break statement.
However, using goto is avoided these days since it makes the program less
readable and complecated.
Syntax:
1. label:
2. //some part of the code;
3. goto label;
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
While Loop: Syntax :
variable initialization ;
while (condition)
statements ;
variable increment or decrement ;
while loop can be addressed as an entry control loop. It is completed in 3 steps.
Variable initialization.( e.g int x=0; )
condition( e.g while( x<=10) )
Variable increment or decrement ( x++ or x-- or x=x+2 )
The while loop is an entry controlled loop statement, i.e means the
condition is evaluated first and it is true, then the body of the loop is
executed. After executing the body of the loop, the condition is once
again evaluated and if it is true, the body is executed once again, the
process of repeated execution of the loop continues until the condition
finally becomes false and the control is transferred out of the loop.
Flowchart:
do-while loop
Syntax : variable initialization ;
do{
statements ;
variable increment or decrement ;
}while (condition);
The do-while loop is an exit controlled loop statement The body of the loop are
executed first and then the condition is evaluated. If it is true, then the body of the
loop is executed once again. The process of execution of body of the loop is
continued until the condition finally becomes false and the control is transferred to
the statement immediately after the loop. The statements are always executed at
least once
Flowchart:
For Loop:
This is an entry controlled looping statement.
In this loop structure, more than one variable can be initialized.
One of the most important features of this loop is that the three actions
can be taken at a time like variable initialization, condition checking
and increment/decrement.
The for loop can be more concise and flexible than that of while and do-while
loops.
Syntax : for(initialization; condition; increment/decrement)
Statements;
}
Flowchart:
Nested for loop: We can also have nested for loops, i.e one for loop inside
another for loop. nesting is often used for handling multidimensional arrays.
Syntax:
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
Continue Statement
Continue is keyword exactly opposite to break. The continue tatement
is used for continuing next iteration of loop statements. When it occurs
in the loop it does not terminate, but it skips some statements inside
the loop / the statements after this statement. . The continue statement
is used/ associated with decision making statement such as if ,if-else.
Syntax of continue Statement
continue;
flowchart: