SlideShare a Scribd company logo
1 of 39
Operators
and
Expressions
Unit 4
Operators
• Symbol that operates on certain data type or data item.
• Used in program to perform certain mathematical or
logical manipulations.
• Ex: in a simple expression 5+6, the symbol “+” is called
an operator which operates on two data items 5 and 6.
• The data items that operator act upon are called
operands.
Ashim Lamichhane 2
Expression
• An expression is a combination of variables,
constants and operators written according to
syntax of the language.
• Ex:
8+10 a+c*d a>b a/c
Ashim Lamichhane 3
• We can classify operators into
– Unary operators
• Which requires only one operand
• Ex. ++ , --, +,-
– Binary operators
• Which requires two operands
• Ex. +,-,*, / , < , > etc.
– Ternary operators
• Which require three operands
• Ex. “ ?: ” (conditional operator)
Ashim Lamichhane 4
• Ternary operators can be further classified
into following categories:
–Arithmetic Operators
–Relational Operators
–Logical Operators
–Assignment Operators
–Increment and Decrement Operators
–Conditional Operators
–Bitwise Operators
–Special Operators
Ashim Lamichhane 5
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20
then
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = 10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B / A = 2
% Modulus Operator and remainder of after an integer
division.
B % A = 0
++ Increment operator increases the integer value by
one.
A++ = 11
-- Decrement operator decreases the integer value by
one.
A-- = 9
Ashim Lamichhane 6
Integer Arithmetic
• Division Rule
– Int / int =int
– Float / float= float
– Int / float = float
– Float /int =float
Ashim Lamichhane 7
#include <stdio.h>
Void main() {
int a = 21; int b = 10; int c ;
c = a + b;
printf("Line 1 - Value of c is %dn", c );
c = a - b;
printf("Line 2 - Value of c is %dn", c );
c = a * b;
printf("Line 3 - Value of c is %dn", c );
c = a / b;
printf("Line 4 - Value of c is %dn", c );
c = a % b;
printf("Line 5 - Value of c is %dn", c );
c = a++;
printf("Line 6 - Value of c is %dn", c );
c = a--;
printf("Line 7 - Value of c is %dn", c );
}
Ashim Lamichhane 8
Relational Operators
Assume variable A holds 10 and variable B holds 20
Operator Description Example
== Checks if the values of two operands are equal
or not. If yes, then the condition becomes true.
(A == B) is not true.
!= Checks if the values of two operands are equal
or not. If the values are not equal, then the
condition becomes true.
(A != B) is true.
> Checks if the value of left operand is greater
than the value of right operand. If yes, then the
condition becomes true.
(A > B) is not true.
< Checks if the value of left operand is less than
the value of right operand. If yes, then the
condition becomes true.
(A < B) is true.
>= Checks if the value of left operand is greater
than or equal to the value of right operand. If
yes, then the condition becomes true.
(A >= B) is not true.
<= Checks if the value of left operand is less than
or equal to the value of right operand. If yes,
then the condition becomes true.
(A <= B) is true.
Ashim Lamichhane 9
#include <stdio.h>
main() {
int a = 21; int b = 10; int c ;
if( a == b ) {
printf("Line 1 - a is equal to bn" );
}
else {
printf("Line 1 - a is not equal to bn" );
}
if ( a < b ) {
printf("Line 2 - a is less than bn" );
}
else {
printf("Line 2 - a is not less than bn" );
}
if ( a > b ) {
printf("Line 3 - a is greater than bn" );
}
else {
printf("Line 3 - a is not greater than bn" );
}
/* Lets change value of a and b */
a = 5; b = 20;
if ( a <= b ) {
printf("Line 4 - a is either less than or equal to bn" );
}
if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to bn" );
}
}
Ashim Lamichhane 10
Logical Operators
Assume variable A holds 1 and variable B holds 0
Operator Description Example
&& Called Logical AND operator. If both the
operands are non-zero, then the condition
becomes true.
(A && B) is false.
|| Called Logical OR Operator. If any of the two
operands is non-zero, then the condition
becomes true.
(A || B) is true.
! Called Logical NOT Operator. It is used to
reverse the logical state of its operand. If a
condition is true, then Logical NOT operator will
make it false.
!(A && B) is true.
Ashim Lamichhane 11
Void main() {
int a = 5; int b = 20; int c ;
if ( a && b ) {
printf("Line 1 - Condition is truen" );
}
if ( a || b ) {
printf("Line 2 - Condition is truen" );
}
/* lets change the value of a and b */
a = 0; b = 10;
if ( a && b ) {
printf("Line 3 - Condition is truen" );
} else
{
printf("Line 3 - Condition is not truen" );
}
if ( !(a && b) ) {
printf("Line 4 - Condition is truen" );
}
}
Ashim Lamichhane 12
Assignment Operators
Operator Description Example
= Simple assignment operator. Assigns values from
right side operands to left side operand
C = A + B will assign the
value of A + B to C
+= Add AND assignment operator. It adds the right
operand to the left operand and assign the
result to the left operand.
C += A is equivalent to C =
C + A
-= Subtract AND assignment operator. It subtracts
the right operand from the left operand and
assigns the result to the left operand.
C -= A is equivalent to C =
C - A
*= Multiply AND assignment operator. It multiplies
the right operand with the left operand and
assigns the result to the left operand.
C *= A is equivalent to C =
C * A
/= Divide AND assignment operator. It divides the
left operand with the right operand and assigns
the result to the left operand.
C /= A is equivalent to C =
C / A
%= Modulus AND assignment operator. It takes
modulus using two operands and assigns the
result to the left operand.
C %= A is equivalent to C =
C % A
Ashim Lamichhane 13
Increment And Decrement Operators
• Increment operator is used to increase the
value of an operand by 1
• Decrement operator is used to decrease the
value of an operand by 1
Operator Description Example
++ ++variable (prefix notation) Variable = variable + 1
++ variable++ (postfix notation) Variable= variable + 1
-- - -variable (prefix notation) Variable =variable - 1
-- variable- - (postfix notation) Variable =variable - 1
Ashim Lamichhane 14
void main(){
int a= 10;
clrscr();
printf("a =%d",a);
printf("a =%d",++a);
printf("a =%d",a++);
printf("a =%d",a);
}
Ashim Lamichhane 15
void main(){
int a= 10;
clrscr();
printf("a =%d",a);
printf("a =%d",++a);
printf("a =%d",a++);
printf("a =%d",a);
}
OUTPUT:
a=10
a=11
a=11
a=12
Ashim Lamichhane 16
Conditional Operator
• The operator pair “?:” is known as conditional operator.
• It takes three operands. Also called ternary operator.
• General form:
expression1 ? expression 2 : expression 3
• expression1 is evaluated first
If expression1 is true
then value of expression2 is the value of condition
expression
else
the value of expression3 is the value of conditional
expression
Ashim Lamichhane 17
void main()
{
int n1,n2, larger;
clrscr();
printf("Enter Two numbers:");
scanf("%d%d",&n1,&n2);
larger= n1>n2 ? n1 : n2;
printf("The larger number is %d", larger);
getch();
}
Ashim Lamichhane 18
Bitwise Logical Operator
• Bitwise operators are used for manipulating data at bit level.
• These operators are used for testing the bits or shifting them to the
left or to the right.
• Can be applied only to integer-type operands and not to float or
double.
• Three types of bitwise operators
– Bitwise logical operators
– Bitwise shift operators
– One’s complement operator
Ashim Lamichhane 19
Bitwise logical Operators
• Performs logical tests between two integer-type operands.
• These operators work on their operands bit-by-bit starting
from the least significant(i.e rightmost) bit.
• Three logical bitwise operators
– Bitwise AND(&)
– Bitwise OR( | )
– Bitwise Exclusive OR (^)
Ashim Lamichhane 20
Bitwise And (&)
• Logical ANDing between two operands.
• The result of ANDing operation is 1 if both the bits
have a value of 1; otherwise it is 0.
• Consider n1=60 and n2=15
– N1 0000 0000 0011 1100
– N2 0000 0000 0000 1111
• If n3= n1 & n2;
– n3  0000 0000 0000 1100
Ashim Lamichhane 21
Bitwise OR( | )
• ORing between two operands
• The result of Oring operations is 1 if either of the bits have
value of 1; otherwise it is 0.
• Consider n1=60 and n2=15
– N1 0000 0000 0011 1100
– N2 0000 0000 0000 1111
• If n3= n1 | n2;
– n3  0000 0000 0011 1111
Ashim Lamichhane 22
Bitwise Exclusive XOR ( ^ )
• The result of Exclusive ORing operations is 1 only
if one of the bits have a value of 1; otherwise it is
0.
• Consider n1=60 and n2=15
– N1 0000 0000 0011 1100
– N2 0000 0000 0000 1111
• If n3= n1 & n2;
– n3  0000 0000 0011 0011
Ashim Lamichhane 23
#include<stdio.h>
void main(){
int n1=60,n2=51,AND, OR, XOR;
AND= n1 & n2;
OR= n1 | n2;
XOR= n1 ^ n2;
printf("AND=%dn",AND );
printf("OR=%dn",OR );
printf("XOR=%dn",XOR );
}
Ashim Lamichhane 24
Bitwise Shift Operators
• Are used to move bit patterns either to the
left or to the right.
• There are two bitwise shift operators
– Left shift ( << )
– Right shift ( >> )
Ashim Lamichhane 25
• Left Shift ( << )
– Causes the operand to be shifted to the left by n
positions.
• operand << n
– The leftmost n bits in the original bit pattern will
be lost and the rightmost n bits empty positions
will be filled with 0’s.
– Ex n1=60
• Execute the statement n2= n1 <<3;
n1 0000 0000 0011 1100
Shift 1 0000 0000 0111 1000
Shift 2 0000 0000 1111 0000
Shift 3 0000 0001 1110 0000 (==n2)
Ashim Lamichhane 26
• Right Shift ( >> )
– Causes the operand to be shifted to the right by n
positions.
• operand >> n
– The empty leftmost n bits positions will be filled
with 0’s, if the operand is an unsigned integer.
– Ex unsigned int n1=60;
• Execute the statement n2= n1 >>3;
n1 0000 0000 0011 1100
Shift 1 0000 0000 0001 1110
Shift 2 0000 0000 0000 1111
Shift 3 0000 0000 0000 0111 (==n2)
Ashim Lamichhane 27
Bitwise One’s Complement Operator
• Is a unary operator which inverts all the bits
represented by its operand.
• This means that all 0s becomes 1s and 1s
becomes 0s
– If n1=60, then we execute the statement
• n2= ~n1
– The resulting bit pattern represents the decimal:
-61
Ashim Lamichhane 28
#include<stdio.h>
voidmain(){
unsigned int n1=60 ,left, right;
left =n1 << 3;
right =n1 >> 3;
printf("%d n", left);
printf("%dn", right);
}
Ashim Lamichhane 29
Special Operators
• C supports some special operators and for
now we discuss
– comma operator (,)
– sizeof operator
Ashim Lamichhane 30
Comma operator
• The comma operator can be used to link related expressions
together.
• A comma-linked list of expressions are evaluated from left-to-
right and the value of the rightmost expression is the value of
the combined expressions.
• Ex: n3=(n1=50, n2=10,n1+n2)
– The first assign the value 50 to n1
– Assign the value 10 to n2
– Assign sum n1+n2 to n3
Ashim Lamichhane 31
sizeof Operator
• Is used with an operand to return the number
of bytes it occupies.
• The operand may be constant, variable or a
data type qualifier.
Ashim Lamichhane 32
#include<stdio.h>
Void main(){
unsigned int n1;
printf("Integer Variable =>
%lun",sizeof(n1) );
printf("Double Constant =>
%lun",sizeof(15.11) );
printf("Long int Data type qualifier =>
%lun",sizeof(15L) );
}
Ashim Lamichhane 33
Operator precedence and associativity
• The precedence is used to determine how an expression
involving more than one operator is evaluated.
• There are distinct level of precedence.
• The operators at the higher level of precedence are evaluated
first.
• Operators of same precedence are evaluated either from “left
to right” or “right to left” depending on the level also known
as associativity.
Ashim Lamichhane 34
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 rightAshim Lamichhane 35
• Ex” consider four integer type variable n1=9
n2=12 n3=3 and x
x = n1 –n2 / 3 + n3 *2 -1
Becomes,
x= 9 -12 /3 + 3 * 2 -1
Step1: 9 -12 / 6 * (2-1)
Step2: 9-12/6*1
Step3: 9-2*1
Step4: 9-2
Step5: 7
Ashim Lamichhane 36
• Example x=20 and y=5
• If(x==10+15 && y<10)
– Step1: If(x==25 && y<10)
– Step2: if(20==25 && 5 < 10)
– Step3: if(20==25 && TRUE)
– Step3: if(FALSE && TRUE)
• Since one condition is FALSE, the whole condition
is FALSE.
Ashim Lamichhane 37
Solve this
• Find the value of “a” in each of the following
statements:
– int i = 3, j = 4, k =8;
– float a = 4.5, b = 6.5, c = 3.5;
• a=b-i/k+c/k
• a = (b-k)/j + (j+c)/k
• a = c - ((i+j)/(k+i)) *b
• a=c-i+j/k+i*b
• a=c+j%2+b
• a=(b+1)%(c+1)
Ashim Lamichhane 38
END
Ashim Lamichhane 39

More Related Content

What's hot

constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
Sahithi Naraparaju
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
vishaljot_kaur
 

What's hot (20)

Operator precedence and associativity
Operator precedence and associativityOperator precedence and associativity
Operator precedence and associativity
 
File handling in c
File handling in cFile handling in c
File handling in c
 
C program
C programC program
C program
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Python Basics
Python Basics Python Basics
Python Basics
 
Type conversion
Type conversionType conversion
Type conversion
 
C string
C stringC string
C string
 
for loop in java
for loop in java for loop in java
for loop in java
 
Basic Structure of C Language and Related Term
Basic Structure of C Language  and Related TermBasic Structure of C Language  and Related Term
Basic Structure of C Language and Related Term
 
15 bitwise operators
15 bitwise operators15 bitwise operators
15 bitwise operators
 
Evaluation of postfix expression
Evaluation of postfix expressionEvaluation of postfix expression
Evaluation of postfix expression
 
Loops c++
Loops c++Loops c++
Loops c++
 
C functions
C functionsC functions
C functions
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
 
Tokens in C++
Tokens in C++Tokens in C++
Tokens in C++
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Input output statement in C
Input output statement in CInput output statement in C
Input output statement in C
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 

Viewers also liked

Viewers also liked (12)

File handling in c
File handling in c File handling in c
File handling in c
 
Unit 11. Graphics
Unit 11. GraphicsUnit 11. Graphics
Unit 11. Graphics
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
File in c
File in cFile in c
File in c
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
 
File handling in C
File handling in CFile handling in C
File handling in C
 

Similar to Unit 4. Operators and Expression

C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
jahanullah
 

Similar to Unit 4. Operators and Expression (20)

Theory3
Theory3Theory3
Theory3
 
Programming Fundamentals lecture 7
Programming Fundamentals lecture 7Programming Fundamentals lecture 7
Programming Fundamentals lecture 7
 
C operators
C operatorsC operators
C operators
 
Operators in c by anupam
Operators in c by anupamOperators in c by anupam
Operators in c by anupam
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
Operators inc c language
Operators inc c languageOperators inc c language
Operators inc c language
 
Operators
OperatorsOperators
Operators
 
C Operators and Control Structures.pptx
C Operators and Control Structures.pptxC Operators and Control Structures.pptx
C Operators and Control Structures.pptx
 
C operators
C operators C operators
C operators
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
 
COM1407: C Operators
COM1407: C OperatorsCOM1407: C Operators
COM1407: C Operators
 
Types of Operators in C
Types of Operators in CTypes of Operators in C
Types of Operators in C
 
C++ revision add on till now
C++ revision add on till nowC++ revision add on till now
C++ revision add on till now
 
C++ revision add on till now
C++ revision add on till nowC++ revision add on till now
C++ revision add on till now
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
C Operators and Control Structures.pdf
C Operators and Control Structures.pdfC Operators and Control Structures.pdf
C Operators and Control Structures.pdf
 
Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++
 
python operators.ppt
python operators.pptpython operators.ppt
python operators.ppt
 

More from Ashim Lamichhane

More from Ashim Lamichhane (10)

Searching
SearchingSearching
Searching
 
Sorting
SortingSorting
Sorting
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Linked List
Linked ListLinked List
Linked List
 
Queues
QueuesQueues
Queues
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Algorithm big o
Algorithm big oAlgorithm big o
Algorithm big o
 
Algorithm Introduction
Algorithm IntroductionAlgorithm Introduction
Algorithm Introduction
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structure
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Recently uploaded (20)

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

Unit 4. Operators and Expression

  • 2. Operators • Symbol that operates on certain data type or data item. • Used in program to perform certain mathematical or logical manipulations. • Ex: in a simple expression 5+6, the symbol “+” is called an operator which operates on two data items 5 and 6. • The data items that operator act upon are called operands. Ashim Lamichhane 2
  • 3. Expression • An expression is a combination of variables, constants and operators written according to syntax of the language. • Ex: 8+10 a+c*d a>b a/c Ashim Lamichhane 3
  • 4. • We can classify operators into – Unary operators • Which requires only one operand • Ex. ++ , --, +,- – Binary operators • Which requires two operands • Ex. +,-,*, / , < , > etc. – Ternary operators • Which require three operands • Ex. “ ?: ” (conditional operator) Ashim Lamichhane 4
  • 5. • Ternary operators can be further classified into following categories: –Arithmetic Operators –Relational Operators –Logical Operators –Assignment Operators –Increment and Decrement Operators –Conditional Operators –Bitwise Operators –Special Operators Ashim Lamichhane 5
  • 6. Arithmetic Operators Assume variable A holds 10 and variable B holds 20 then Operator Description Example + Adds two operands. A + B = 30 − Subtracts second operand from the first. A − B = 10 * Multiplies both operands. A * B = 200 / Divides numerator by de-numerator. B / A = 2 % Modulus Operator and remainder of after an integer division. B % A = 0 ++ Increment operator increases the integer value by one. A++ = 11 -- Decrement operator decreases the integer value by one. A-- = 9 Ashim Lamichhane 6
  • 7. Integer Arithmetic • Division Rule – Int / int =int – Float / float= float – Int / float = float – Float /int =float Ashim Lamichhane 7
  • 8. #include <stdio.h> Void main() { int a = 21; int b = 10; int c ; c = a + b; printf("Line 1 - Value of c is %dn", c ); c = a - b; printf("Line 2 - Value of c is %dn", c ); c = a * b; printf("Line 3 - Value of c is %dn", c ); c = a / b; printf("Line 4 - Value of c is %dn", c ); c = a % b; printf("Line 5 - Value of c is %dn", c ); c = a++; printf("Line 6 - Value of c is %dn", c ); c = a--; printf("Line 7 - Value of c is %dn", c ); } Ashim Lamichhane 8
  • 9. Relational Operators Assume variable A holds 10 and variable B holds 20 Operator Description Example == Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A <= B) is true. Ashim Lamichhane 9
  • 10. #include <stdio.h> main() { int a = 21; int b = 10; int c ; if( a == b ) { printf("Line 1 - a is equal to bn" ); } else { printf("Line 1 - a is not equal to bn" ); } if ( a < b ) { printf("Line 2 - a is less than bn" ); } else { printf("Line 2 - a is not less than bn" ); } if ( a > b ) { printf("Line 3 - a is greater than bn" ); } else { printf("Line 3 - a is not greater than bn" ); } /* Lets change value of a and b */ a = 5; b = 20; if ( a <= b ) { printf("Line 4 - a is either less than or equal to bn" ); } if ( b >= a ) { printf("Line 5 - b is either greater than or equal to bn" ); } } Ashim Lamichhane 10
  • 11. Logical Operators Assume variable A holds 1 and variable B holds 0 Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true. ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. !(A && B) is true. Ashim Lamichhane 11
  • 12. Void main() { int a = 5; int b = 20; int c ; if ( a && b ) { printf("Line 1 - Condition is truen" ); } if ( a || b ) { printf("Line 2 - Condition is truen" ); } /* lets change the value of a and b */ a = 0; b = 10; if ( a && b ) { printf("Line 3 - Condition is truen" ); } else { printf("Line 3 - Condition is not truen" ); } if ( !(a && b) ) { printf("Line 4 - Condition is truen" ); } } Ashim Lamichhane 12
  • 13. Assignment Operators Operator Description Example = Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C += Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A -= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A *= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A %= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A Ashim Lamichhane 13
  • 14. Increment And Decrement Operators • Increment operator is used to increase the value of an operand by 1 • Decrement operator is used to decrease the value of an operand by 1 Operator Description Example ++ ++variable (prefix notation) Variable = variable + 1 ++ variable++ (postfix notation) Variable= variable + 1 -- - -variable (prefix notation) Variable =variable - 1 -- variable- - (postfix notation) Variable =variable - 1 Ashim Lamichhane 14
  • 15. void main(){ int a= 10; clrscr(); printf("a =%d",a); printf("a =%d",++a); printf("a =%d",a++); printf("a =%d",a); } Ashim Lamichhane 15
  • 16. void main(){ int a= 10; clrscr(); printf("a =%d",a); printf("a =%d",++a); printf("a =%d",a++); printf("a =%d",a); } OUTPUT: a=10 a=11 a=11 a=12 Ashim Lamichhane 16
  • 17. Conditional Operator • The operator pair “?:” is known as conditional operator. • It takes three operands. Also called ternary operator. • General form: expression1 ? expression 2 : expression 3 • expression1 is evaluated first If expression1 is true then value of expression2 is the value of condition expression else the value of expression3 is the value of conditional expression Ashim Lamichhane 17
  • 18. void main() { int n1,n2, larger; clrscr(); printf("Enter Two numbers:"); scanf("%d%d",&n1,&n2); larger= n1>n2 ? n1 : n2; printf("The larger number is %d", larger); getch(); } Ashim Lamichhane 18
  • 19. Bitwise Logical Operator • Bitwise operators are used for manipulating data at bit level. • These operators are used for testing the bits or shifting them to the left or to the right. • Can be applied only to integer-type operands and not to float or double. • Three types of bitwise operators – Bitwise logical operators – Bitwise shift operators – One’s complement operator Ashim Lamichhane 19
  • 20. Bitwise logical Operators • Performs logical tests between two integer-type operands. • These operators work on their operands bit-by-bit starting from the least significant(i.e rightmost) bit. • Three logical bitwise operators – Bitwise AND(&) – Bitwise OR( | ) – Bitwise Exclusive OR (^) Ashim Lamichhane 20
  • 21. Bitwise And (&) • Logical ANDing between two operands. • The result of ANDing operation is 1 if both the bits have a value of 1; otherwise it is 0. • Consider n1=60 and n2=15 – N1 0000 0000 0011 1100 – N2 0000 0000 0000 1111 • If n3= n1 & n2; – n3  0000 0000 0000 1100 Ashim Lamichhane 21
  • 22. Bitwise OR( | ) • ORing between two operands • The result of Oring operations is 1 if either of the bits have value of 1; otherwise it is 0. • Consider n1=60 and n2=15 – N1 0000 0000 0011 1100 – N2 0000 0000 0000 1111 • If n3= n1 | n2; – n3  0000 0000 0011 1111 Ashim Lamichhane 22
  • 23. Bitwise Exclusive XOR ( ^ ) • The result of Exclusive ORing operations is 1 only if one of the bits have a value of 1; otherwise it is 0. • Consider n1=60 and n2=15 – N1 0000 0000 0011 1100 – N2 0000 0000 0000 1111 • If n3= n1 & n2; – n3  0000 0000 0011 0011 Ashim Lamichhane 23
  • 24. #include<stdio.h> void main(){ int n1=60,n2=51,AND, OR, XOR; AND= n1 & n2; OR= n1 | n2; XOR= n1 ^ n2; printf("AND=%dn",AND ); printf("OR=%dn",OR ); printf("XOR=%dn",XOR ); } Ashim Lamichhane 24
  • 25. Bitwise Shift Operators • Are used to move bit patterns either to the left or to the right. • There are two bitwise shift operators – Left shift ( << ) – Right shift ( >> ) Ashim Lamichhane 25
  • 26. • Left Shift ( << ) – Causes the operand to be shifted to the left by n positions. • operand << n – The leftmost n bits in the original bit pattern will be lost and the rightmost n bits empty positions will be filled with 0’s. – Ex n1=60 • Execute the statement n2= n1 <<3; n1 0000 0000 0011 1100 Shift 1 0000 0000 0111 1000 Shift 2 0000 0000 1111 0000 Shift 3 0000 0001 1110 0000 (==n2) Ashim Lamichhane 26
  • 27. • Right Shift ( >> ) – Causes the operand to be shifted to the right by n positions. • operand >> n – The empty leftmost n bits positions will be filled with 0’s, if the operand is an unsigned integer. – Ex unsigned int n1=60; • Execute the statement n2= n1 >>3; n1 0000 0000 0011 1100 Shift 1 0000 0000 0001 1110 Shift 2 0000 0000 0000 1111 Shift 3 0000 0000 0000 0111 (==n2) Ashim Lamichhane 27
  • 28. Bitwise One’s Complement Operator • Is a unary operator which inverts all the bits represented by its operand. • This means that all 0s becomes 1s and 1s becomes 0s – If n1=60, then we execute the statement • n2= ~n1 – The resulting bit pattern represents the decimal: -61 Ashim Lamichhane 28
  • 29. #include<stdio.h> voidmain(){ unsigned int n1=60 ,left, right; left =n1 << 3; right =n1 >> 3; printf("%d n", left); printf("%dn", right); } Ashim Lamichhane 29
  • 30. Special Operators • C supports some special operators and for now we discuss – comma operator (,) – sizeof operator Ashim Lamichhane 30
  • 31. Comma operator • The comma operator can be used to link related expressions together. • A comma-linked list of expressions are evaluated from left-to- right and the value of the rightmost expression is the value of the combined expressions. • Ex: n3=(n1=50, n2=10,n1+n2) – The first assign the value 50 to n1 – Assign the value 10 to n2 – Assign sum n1+n2 to n3 Ashim Lamichhane 31
  • 32. sizeof Operator • Is used with an operand to return the number of bytes it occupies. • The operand may be constant, variable or a data type qualifier. Ashim Lamichhane 32
  • 33. #include<stdio.h> Void main(){ unsigned int n1; printf("Integer Variable => %lun",sizeof(n1) ); printf("Double Constant => %lun",sizeof(15.11) ); printf("Long int Data type qualifier => %lun",sizeof(15L) ); } Ashim Lamichhane 33
  • 34. Operator precedence and associativity • The precedence is used to determine how an expression involving more than one operator is evaluated. • There are distinct level of precedence. • The operators at the higher level of precedence are evaluated first. • Operators of same precedence are evaluated either from “left to right” or “right to left” depending on the level also known as associativity. Ashim Lamichhane 34
  • 35. 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 rightAshim Lamichhane 35
  • 36. • Ex” consider four integer type variable n1=9 n2=12 n3=3 and x x = n1 –n2 / 3 + n3 *2 -1 Becomes, x= 9 -12 /3 + 3 * 2 -1 Step1: 9 -12 / 6 * (2-1) Step2: 9-12/6*1 Step3: 9-2*1 Step4: 9-2 Step5: 7 Ashim Lamichhane 36
  • 37. • Example x=20 and y=5 • If(x==10+15 && y<10) – Step1: If(x==25 && y<10) – Step2: if(20==25 && 5 < 10) – Step3: if(20==25 && TRUE) – Step3: if(FALSE && TRUE) • Since one condition is FALSE, the whole condition is FALSE. Ashim Lamichhane 37
  • 38. Solve this • Find the value of “a” in each of the following statements: – int i = 3, j = 4, k =8; – float a = 4.5, b = 6.5, c = 3.5; • a=b-i/k+c/k • a = (b-k)/j + (j+c)/k • a = c - ((i+j)/(k+i)) *b • a=c-i+j/k+i*b • a=c+j%2+b • a=(b+1)%(c+1) Ashim Lamichhane 38