SlideShare a Scribd company logo
1 of 48
COM1407
Computer Programming
Lecture 05
C Operators
K.A.S.H. Kulathilake
B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK)
Rajarata University of Sri Lanka
Department of Physical Sciences
1
Objectives
• At the end of this lecture students should be able
to;
▫ Define the terms operators, operands, operator
precedence and associativity.
▫ Describe operators in C programming language.
▫ Practice the effect of different operators in C
programming language.
▫ Justify evaluation of expressions in programming.
▫ Apply taught concepts for writing programs.
2
Operators and Operands
• Operands
▫ Operands are numerical, text and Boolean values
that a program can manipulate and use as logical
guidelines for making decisions.
▫ Like with math, computer programs can use
constant values and variables as operands.
▫ If you have the variable "dozens" with the value of
“2" and the constant "12" in the equation
"dozens*12 = 24."
▫ Both "dozens" and "12" are operands in the
equation.
3
Operators and Operands (Cont…)
• Operators
▫ Operators are used to manipulate and check
operand values.
▫ In C programming Operators are symbols which
take one or more operands or expressions and
perform arithmetic or logical computations.
▫ If the operator manipulates one operand it is
known as unary operator; if the operator
manipulates two operands, it is known as binary
operator and if the operator manipulates three
operands, it is known as ternary operator.
4
Operators and Operands (Cont…)
• C has following operators
▫ Arithmetic operators  all are binary operators
▫ Logical operators  all are binary operators
▫ Relational operators  all are binary operators
▫ Bitwise operators  all are binary operators except !
and ~
▫ Increment, decrement operators  unary operators
▫ Assignment operators  binary operators
▫ Conditional operator  ternary operator
▫ Type cast operator unary operator
▫ sizeof operator  unary operator
▫ Comma operator  binary operator
5
Arithmetic Operators
Operator Description
A+B adds A with B;
A-B subtracts B from A;
A*B multiplies A by B;
A/B divides A by B;
I%J gives the remainder of I divided by J.
Here I and J are expressions of any integer data type;
6
Here A and B are expressions of any basic data type
Arithmetic Operators (Cont…)
#include <stdio.h>
int main (void)
{
int a = 100;
int b = 2;
int c = 25;
int d = 4;
int result;
result = a - b;
printf ("a - b = %in", result);
result = b * c;
printf ("b * c = %in", result);
result = a / c;
printf ("a / c = %in", result);
result = a + b * c;
printf ("a + b * c = %in", result);
printf ("a * b + c * d = %in", a * b + c * d);
return 0;
}
7
Arithmetic Operators (Cont…)
#include <stdio.h>
int main (void)
{
int a = 25;
int b = 2;
float c = 25.0;
float d = 2.0;
printf ("6 + a / 5 * b = %in", 6 + a / 5 * b);
printf ("a / b * b = %in", a / b * b);
printf ("c / d * d = %fn", c / d * d);
printf ("-a = %in", -a);
return 0;
}
8
Arithmetic Operators (Cont…)
#include <stdio.h>
int main (void)
{
int a = 25, b = 5, c = 10, d = 7;
printf ("a %% b = %in", a % b);
printf ("a %% c = %in", a % c);
printf ("a %% d = %in", a % d);
printf ("a / d * d + a %% d = %in",
a / d * d + a % d);
return 0;
}
9
Logical Operators
• A
10
Operator Description
A && B has the value 1 if both A and B are nonzero, and 0
otherwise (and B is evaluated only if A is nonzero);
A || B has the value 1 if either A or B is nonzero, and 0
otherwise (and B is evaluated only if A is zero);
!A has the value 1 if a is zero, and 0 otherwise.
A and B are expressions of any basic data type except void,
or are both pointers;
Logical Operators (Cont…)
#include <stdio.h>
int main()
{
int a = 5;
int b = 20;
int c = 1;
printf( "( a && b ) = %d n", a && b );
printf( "( a || b ) = %d n", a || b );
printf( " !a = %d n", !a );
return 0;
}
11
Relational Operators
12
Operator Description
A < B has the value 1 if A is less than B, and 0 otherwise;
A <= B has the value 1 if A is less than or equal to B, and 0
otherwise;
A > B has the value 1 if A is greater than B, and 0 otherwise;
A >= B has the value 1 if A is greater than or equal to B, and 0
otherwise;
A == B has the value 1 if A is equal to B, and 0 otherwise;
A != B has the value 1 if A is not equal to B, and 0 otherwise;
A and B are expressions of any basic data type except void,
or are both pointers;
Relational Operators (Cont…)
• The usual arithmetic conversions are performed
on A and B.
• The first four relational tests are only
meaningful for pointers if they both point into
the same array or to members of the same
structure or union.
• The type of the result in each case is int.
13
Relational Operators (Cont…)
#include <stdio.h>
int main()
{
int a = 5;
int b = 20;
int c = 5;
printf( "( a < b ) = %d n", a < b );
printf( "( a <= b ) = %d n", a <= b );
printf( "( a > b ) = %d n", a > b );
printf( "( a >= b ) = %d n", a >= b );
printf( "( c == a ) = %d n", c == a );
printf( "( a != b ) = %d n", a != b );
return 0;
}
14
Bitwise Operators
15
Operator Description
A & B performs a bitwise AND of A and B;
A | B performs a bitwise OR of A and B;
A ^ B performs a bitwise XOR of A and B;
~A takes the ones complement of A;
A << n shifts A to the left n bits;
A >> n shifts A to the right n bits;
A, B, n are expressions of any integer data type;
Bitwise Operators (Cont…)
• The usual arithmetic conversions are performed
on the operands, except with << and >>, in
which case just integral promotion is performed
on each operand.
• If the shift count is negative or is greater than or
equal to the number of bits contained in the
object being shifted, the result of the shift is
undefined.
16
Bitwise Operators (Cont…)
• Bitwise operator works on bits and perform bit-
by-bit operation.
• The truth tables for &, |, and ^ is as follows:
17
p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Bitwise Operators (Cont…)
• Assume A = 60 and B = 13 in binary format, they
will be as follows:
A = 0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
A << 2 = 240 i.e., 1111 0000
A >> 2 = 15 i.e., 0000 1111
18
Bitwise Operators (Cont…)
#include <stdio.h>
int main()
{
int a = 60;
int b = 13;
printf( "( a & b ) = %d n", a & b );
printf( "( a | b ) = %d n", a | b );
printf( "( a ^ b ) = %d n", a ^ b );
printf( "( ~ a ) = %d n", ~a );
printf( "( a << 2 ) = %d n", a << 2);
printf( "( a >> 2 ) = %d n", a >> 2);
return 0;
}
19
Increment and Decrement Operators
20
Operator Description
++A increments A and then uses its value as the value of the
expression;
A++ uses A as the value of the expression and then
increments A;
--A decrements A and then uses its value as the value of the
expression;
A-- uses A as the value of the expression and then
decrements A;
A is a modifiable value expression, whose type is not
qualified as const.
Increment and Decrement Operators
(Cont…)
#include <stdio.h>
int main() {
int a = 21;
int c =10;;
c = a++;
printf( "Line 1 - Value of a and c are : %d - %dn", a, c);
c = ++a;
printf( "Line 2 - Value of a and c are : %d - %dn", a, c);
c = a--;
printf( "Line 3 - Value of a and c are : %d - %dn", a, c);
c = --a;
printf( "Line 4 - Value of a and c are : %d - %dn", a, c);
return 0;
}
21
Assignment Operators
• A = B  stores the value of B into A;
• A op= B applies op to A and B, storing the
result in A.
22
A is a modifiable value expression, whose type is not
qualified as const;
op is any operator that can be used as an assignment
operator ; B is an expression;
Assignment Operators (Cont…)
• In the first expression, if B is one of the basic
data types (except void), it is converted to match
the type of A.
• If A is a pointer, B must be a pointer to the same
type as A, a void pointer, or the null pointer.
• If A is a void pointer, B can be of any pointer
type.
• The second expression is treated as follows;
A = A op (B)
23
Assignment Operators (Cont…)
24
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
Assignment Operators (Cont…)
25
Operator Description Example
<<= 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
Assignment Operators (Cont…)
#include <stdio.h>
int main()
{
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %dn", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %dn", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %dn", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %dn", c );
26
Assignment Operators (Cont…)
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %dn", c );
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %dn", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %dn", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %dn", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %dn", c );
27
Assignment Operators (Cont…)
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %dn", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %dn", c );
return 0;
}
28
Conditional Operators
• Given that A, B, C are expressions; then the
expression
A ? B : C
has as its value B if A is nonzero, and C otherwise;
only expression B or C is evaluated.
In order to generate 1 or 0 for A, it should be a
relational or logical expression.
29
Conditional Operators (Cont…)
• Expressions B and C must be of the same data type.
• If they are not, but are both arithmetic data types,
the usual arithmetic conversions are applied to
make their types the same.
• If one is a pointer and the other is zero, the latter is
taken as a null pointer of the same type as the
former.
• If one is a pointer to void and the other is a pointer
to another type, the latter is converted to a pointer
to void, and that is the resulting type.
30
Conditional Operators (Cont…)
#include<stdio.h>
int main()
{
int num;
int flag;
printf("Enter the Number : ");
scanf("%d",&num);
flag = ((num%2==0)?1:0);
printf ("Flag value : %d n", flag);
return 0;
}
31
Type Cast Operator
• You can convert the values from one type to
another explicitly using the cast operator as
follows:
(type_name) expression
• Refere Lecture 04
32
sizeof Operator
• Given that type is as the name of a basic data
type, an enumerated data type (preceded by the
keyword enum), a typedef-defined type, or is a
derived data type; A is an expression; then the
expression
sizeof (type) has as its value the number of
bytes needed to contain a value of the specified
type;
sizeof A  has as its value the number of bytes
required to hold the result of the evaluation of A.
33
sizeof Operator (Cont…)
#include<stdio.h>
int main() {
int ivar = 100;
char cvar = 'a';
float fvar = 10.10;
double dvar = 18977670.10;
printf("%dn", sizeof(ivar));
printf("%dn", sizeof(cvar));
printf("%dn", sizeof(fvar));
printf("%dn", sizeof(dvar));
return 0;
}
34
Comma Operator
• The comma operator can be used to link the related
expressions together.
• A comma linked expression is evaluated from left to right
and the value of the right most expression is the value of
the combined expression.
x = (a = 2, b = 4, a+b)
• In this example, the expression is evaluated from left to
right.
• So at first, variable ‘a’ is assigned value 2, then variable
‘b’ is assigned value 4 and then value 6 is assigned to the
variable ‘x’.
• Comma operators are commonly used in for loops, while
loops, while exchanging values.
35
Comma Operator (Cont…)
• Comma operator returns the value of the
rightmost operand when multiple comma
operators are used inside an expression.
• Comma Operator Can acts as :
▫ Operator : In the Expression
▫ Separator : Declaring Variable , In Function Call
Parameter List
36
Comma Operator (Cont…)
#include<stdio.h>
int main()
{
int num1 = 1, num2 = 2;
int res, x, a, b;
x = (a = 2, b = 4, a+b);
res = (num1, num2);
printf("%dn", res);
x = (a = 2, b = 4, a+b);
printf("%dn", x);
return 0;
}
37
C Arithmetic Expression
• Arithmetic expression in C is a combination of
variables, constants and operators written in a
proper syntax.
• C can easily handle any complex mathematical
expressions but these mathematical expressions
have to be written in a proper syntax.
38
Operator Precedence & Associativity
• Operator Precedence
▫ When an expression contains multiple operators,
the precedence of the operators controls the order
in which the individual operators are evaluated.
▫ For example, the expression x + y * z is evaluated
as x + (y * z) because the * operator has higher
precedence than the binary + operator.
▫ The precedence of an operator is established by
the definition of its associated grammar
production.
39
Operator Precedence & Associativity
(Cont…)
• Operator Associativity
▫ A higher precedence operator is evaluated before a
lower precedence operator.
▫ If the precedence levels of operators are the same,
then the order of evaluation depends on their
associativity (or, grouping).
40
Operator Precedence & Associativity
(Cont…)
• Example
(1 > 2 + 3 && 4)
This expression is equivalent to:
((1 > (2 + 3)) && 4)
i.e, (2 + 3) executes first resulting into 5 then, first
part of the expression (1 > 5) executes resulting
into 0 (false) then, (0 && 4) executes resulting
into 0 (false)
41
Operator Precedence & Associativity
(Cont…)
(1 > 2 + 3 && 4) can be written as follows;
=((1 > (2 + 3)) && 4)
=((1>5) && 4)
=(0 && 4)
=0
42
Summary of C Operators
• These operators are listed in order of decreasing
precedence.
• Operators grouped together have the same
precedence.
43
Summary of C Operators (Cont…)
44
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
Questions
• Try this out:
▫ 250*2/4+1
▫ 5%2*5/5
▫ 2+300-200/2
▫ 1 && 1 || 0
▫ 1 || 1 +3-4 && 1
45
Objective Re-cap
• Now you should be able to:
▫ Define the terms operators, operands, operator
precedence and associativity.
▫ Describe operators in C programming language.
▫ Practice the effect of different operators in C
programming language.
▫ Justify evaluation of expressions in programming.
▫ Apply taught concepts for writing programs.
46
References
• Chapter 04, Appendix A, section 5 -
Programming in C, 3rd Edition, Stephen G.
Kochan
47
Next: Program Control Structures – Decision Making &
Branching
48

More Related Content

What's hot

02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
Qundeel
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operators
dishti7
 

What's hot (20)

Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 
Stack
StackStack
Stack
 
Python : Operators
Python : OperatorsPython : Operators
Python : Operators
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Managing input and output operations in c
Managing input and output operations in cManaging input and output operations in c
Managing input and output operations in c
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Operators
OperatorsOperators
Operators
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
 
Linear search algorithm
Linear search algorithmLinear search algorithm
Linear search algorithm
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operators
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Bitwise Operators in C
Bitwise Operators in CBitwise Operators in C
Bitwise Operators in C
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
 
virtual function
virtual functionvirtual function
virtual function
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 

Similar to COM1407: C Operators

PROGRAMMING IN C - Operators.pptx
PROGRAMMING IN C - Operators.pptxPROGRAMMING IN C - Operators.pptx
PROGRAMMING IN C - Operators.pptx
Nithya K
 

Similar to COM1407: C Operators (20)

Programming C Part 02
Programming C Part 02Programming C Part 02
Programming C Part 02
 
Theory3
Theory3Theory3
Theory3
 
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
 
C operators
C operatorsC operators
C operators
 
C Operators and Control Structures.pdf
C Operators and Control Structures.pdfC Operators and Control Structures.pdf
C Operators and Control Structures.pdf
 
C – operators and expressions
C – operators and expressionsC – operators and expressions
C – operators and expressions
 
C - programming - Ankit Kumar Singh
C - programming - Ankit Kumar Singh C - programming - Ankit Kumar Singh
C - programming - Ankit Kumar Singh
 
PROGRAMMING IN C - Operators.pptx
PROGRAMMING IN C - Operators.pptxPROGRAMMING IN C - Operators.pptx
PROGRAMMING IN C - Operators.pptx
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in c
 
ICP - Lecture 5
ICP - Lecture 5ICP - Lecture 5
ICP - Lecture 5
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)
 
ppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operatorsppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operators
 
11operator in c#
11operator in c#11operator in c#
11operator in c#
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
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-computer programming and utilzation
Operators-computer programming and utilzationOperators-computer programming and utilzation
Operators-computer programming and utilzation
 
Programming Fundamentals lecture 7
Programming Fundamentals lecture 7Programming Fundamentals lecture 7
Programming Fundamentals lecture 7
 
Operators
OperatorsOperators
Operators
 

More from Hemantha Kulathilake

More from Hemantha Kulathilake (20)

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for English
 
NLP_KASHK:POS Tagging
NLP_KASHK:POS TaggingNLP_KASHK:POS Tagging
NLP_KASHK:POS Tagging
 
NLP_KASHK:Markov Models
NLP_KASHK:Markov ModelsNLP_KASHK:Markov Models
NLP_KASHK:Markov Models
 
NLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram ModelsNLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram Models
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language Model
 
NLP_KASHK:N-Grams
NLP_KASHK:N-GramsNLP_KASHK:N-Grams
NLP_KASHK:N-Grams
 
NLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit DistanceNLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit Distance
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological Parsing
 
NLP_KASHK:Morphology
NLP_KASHK:MorphologyNLP_KASHK:Morphology
NLP_KASHK:Morphology
 
NLP_KASHK:Text Normalization
NLP_KASHK:Text NormalizationNLP_KASHK:Text Normalization
NLP_KASHK:Text Normalization
 
NLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State AutomataNLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State Automata
 
NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions
 
NLP_KASHK: Introduction
NLP_KASHK: Introduction NLP_KASHK: Introduction
NLP_KASHK: Introduction
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation
 
COM1407: Input/ Output Functions
COM1407: Input/ Output FunctionsCOM1407: Input/ Output Functions
COM1407: Input/ Output Functions
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 

Recently uploaded

Recently uploaded (20)

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
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Ữ Â...
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 

COM1407: C Operators

  • 1. COM1407 Computer Programming Lecture 05 C Operators K.A.S.H. Kulathilake B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK) Rajarata University of Sri Lanka Department of Physical Sciences 1
  • 2. Objectives • At the end of this lecture students should be able to; ▫ Define the terms operators, operands, operator precedence and associativity. ▫ Describe operators in C programming language. ▫ Practice the effect of different operators in C programming language. ▫ Justify evaluation of expressions in programming. ▫ Apply taught concepts for writing programs. 2
  • 3. Operators and Operands • Operands ▫ Operands are numerical, text and Boolean values that a program can manipulate and use as logical guidelines for making decisions. ▫ Like with math, computer programs can use constant values and variables as operands. ▫ If you have the variable "dozens" with the value of “2" and the constant "12" in the equation "dozens*12 = 24." ▫ Both "dozens" and "12" are operands in the equation. 3
  • 4. Operators and Operands (Cont…) • Operators ▫ Operators are used to manipulate and check operand values. ▫ In C programming Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations. ▫ If the operator manipulates one operand it is known as unary operator; if the operator manipulates two operands, it is known as binary operator and if the operator manipulates three operands, it is known as ternary operator. 4
  • 5. Operators and Operands (Cont…) • C has following operators ▫ Arithmetic operators  all are binary operators ▫ Logical operators  all are binary operators ▫ Relational operators  all are binary operators ▫ Bitwise operators  all are binary operators except ! and ~ ▫ Increment, decrement operators  unary operators ▫ Assignment operators  binary operators ▫ Conditional operator  ternary operator ▫ Type cast operator unary operator ▫ sizeof operator  unary operator ▫ Comma operator  binary operator 5
  • 6. Arithmetic Operators Operator Description A+B adds A with B; A-B subtracts B from A; A*B multiplies A by B; A/B divides A by B; I%J gives the remainder of I divided by J. Here I and J are expressions of any integer data type; 6 Here A and B are expressions of any basic data type
  • 7. Arithmetic Operators (Cont…) #include <stdio.h> int main (void) { int a = 100; int b = 2; int c = 25; int d = 4; int result; result = a - b; printf ("a - b = %in", result); result = b * c; printf ("b * c = %in", result); result = a / c; printf ("a / c = %in", result); result = a + b * c; printf ("a + b * c = %in", result); printf ("a * b + c * d = %in", a * b + c * d); return 0; } 7
  • 8. Arithmetic Operators (Cont…) #include <stdio.h> int main (void) { int a = 25; int b = 2; float c = 25.0; float d = 2.0; printf ("6 + a / 5 * b = %in", 6 + a / 5 * b); printf ("a / b * b = %in", a / b * b); printf ("c / d * d = %fn", c / d * d); printf ("-a = %in", -a); return 0; } 8
  • 9. Arithmetic Operators (Cont…) #include <stdio.h> int main (void) { int a = 25, b = 5, c = 10, d = 7; printf ("a %% b = %in", a % b); printf ("a %% c = %in", a % c); printf ("a %% d = %in", a % d); printf ("a / d * d + a %% d = %in", a / d * d + a % d); return 0; } 9
  • 10. Logical Operators • A 10 Operator Description A && B has the value 1 if both A and B are nonzero, and 0 otherwise (and B is evaluated only if A is nonzero); A || B has the value 1 if either A or B is nonzero, and 0 otherwise (and B is evaluated only if A is zero); !A has the value 1 if a is zero, and 0 otherwise. A and B are expressions of any basic data type except void, or are both pointers;
  • 11. Logical Operators (Cont…) #include <stdio.h> int main() { int a = 5; int b = 20; int c = 1; printf( "( a && b ) = %d n", a && b ); printf( "( a || b ) = %d n", a || b ); printf( " !a = %d n", !a ); return 0; } 11
  • 12. Relational Operators 12 Operator Description A < B has the value 1 if A is less than B, and 0 otherwise; A <= B has the value 1 if A is less than or equal to B, and 0 otherwise; A > B has the value 1 if A is greater than B, and 0 otherwise; A >= B has the value 1 if A is greater than or equal to B, and 0 otherwise; A == B has the value 1 if A is equal to B, and 0 otherwise; A != B has the value 1 if A is not equal to B, and 0 otherwise; A and B are expressions of any basic data type except void, or are both pointers;
  • 13. Relational Operators (Cont…) • The usual arithmetic conversions are performed on A and B. • The first four relational tests are only meaningful for pointers if they both point into the same array or to members of the same structure or union. • The type of the result in each case is int. 13
  • 14. Relational Operators (Cont…) #include <stdio.h> int main() { int a = 5; int b = 20; int c = 5; printf( "( a < b ) = %d n", a < b ); printf( "( a <= b ) = %d n", a <= b ); printf( "( a > b ) = %d n", a > b ); printf( "( a >= b ) = %d n", a >= b ); printf( "( c == a ) = %d n", c == a ); printf( "( a != b ) = %d n", a != b ); return 0; } 14
  • 15. Bitwise Operators 15 Operator Description A & B performs a bitwise AND of A and B; A | B performs a bitwise OR of A and B; A ^ B performs a bitwise XOR of A and B; ~A takes the ones complement of A; A << n shifts A to the left n bits; A >> n shifts A to the right n bits; A, B, n are expressions of any integer data type;
  • 16. Bitwise Operators (Cont…) • The usual arithmetic conversions are performed on the operands, except with << and >>, in which case just integral promotion is performed on each operand. • If the shift count is negative or is greater than or equal to the number of bits contained in the object being shifted, the result of the shift is undefined. 16
  • 17. Bitwise Operators (Cont…) • Bitwise operator works on bits and perform bit- by-bit operation. • The truth tables for &, |, and ^ is as follows: 17 p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1
  • 18. Bitwise Operators (Cont…) • Assume A = 60 and B = 13 in binary format, they will be as follows: A = 0011 1100 B = 0000 1101 A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 A << 2 = 240 i.e., 1111 0000 A >> 2 = 15 i.e., 0000 1111 18
  • 19. Bitwise Operators (Cont…) #include <stdio.h> int main() { int a = 60; int b = 13; printf( "( a & b ) = %d n", a & b ); printf( "( a | b ) = %d n", a | b ); printf( "( a ^ b ) = %d n", a ^ b ); printf( "( ~ a ) = %d n", ~a ); printf( "( a << 2 ) = %d n", a << 2); printf( "( a >> 2 ) = %d n", a >> 2); return 0; } 19
  • 20. Increment and Decrement Operators 20 Operator Description ++A increments A and then uses its value as the value of the expression; A++ uses A as the value of the expression and then increments A; --A decrements A and then uses its value as the value of the expression; A-- uses A as the value of the expression and then decrements A; A is a modifiable value expression, whose type is not qualified as const.
  • 21. Increment and Decrement Operators (Cont…) #include <stdio.h> int main() { int a = 21; int c =10;; c = a++; printf( "Line 1 - Value of a and c are : %d - %dn", a, c); c = ++a; printf( "Line 2 - Value of a and c are : %d - %dn", a, c); c = a--; printf( "Line 3 - Value of a and c are : %d - %dn", a, c); c = --a; printf( "Line 4 - Value of a and c are : %d - %dn", a, c); return 0; } 21
  • 22. Assignment Operators • A = B  stores the value of B into A; • A op= B applies op to A and B, storing the result in A. 22 A is a modifiable value expression, whose type is not qualified as const; op is any operator that can be used as an assignment operator ; B is an expression;
  • 23. Assignment Operators (Cont…) • In the first expression, if B is one of the basic data types (except void), it is converted to match the type of A. • If A is a pointer, B must be a pointer to the same type as A, a void pointer, or the null pointer. • If A is a void pointer, B can be of any pointer type. • The second expression is treated as follows; A = A op (B) 23
  • 24. Assignment Operators (Cont…) 24 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
  • 25. Assignment Operators (Cont…) 25 Operator Description Example <<= 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
  • 26. Assignment Operators (Cont…) #include <stdio.h> int main() { int a = 21; int c ; c = a; printf("Line 1 - = Operator Example, Value of c = %dn", c ); c += a; printf("Line 2 - += Operator Example, Value of c = %dn", c ); c -= a; printf("Line 3 - -= Operator Example, Value of c = %dn", c ); c *= a; printf("Line 4 - *= Operator Example, Value of c = %dn", c ); 26
  • 27. Assignment Operators (Cont…) c /= a; printf("Line 5 - /= Operator Example, Value of c = %dn", c ); c = 200; c %= a; printf("Line 6 - %= Operator Example, Value of c = %dn", c ); c <<= 2; printf("Line 7 - <<= Operator Example, Value of c = %dn", c ); c >>= 2; printf("Line 8 - >>= Operator Example, Value of c = %dn", c ); c &= 2; printf("Line 9 - &= Operator Example, Value of c = %dn", c ); 27
  • 28. Assignment Operators (Cont…) c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %dn", c ); c |= 2; printf("Line 11 - |= Operator Example, Value of c = %dn", c ); return 0; } 28
  • 29. Conditional Operators • Given that A, B, C are expressions; then the expression A ? B : C has as its value B if A is nonzero, and C otherwise; only expression B or C is evaluated. In order to generate 1 or 0 for A, it should be a relational or logical expression. 29
  • 30. Conditional Operators (Cont…) • Expressions B and C must be of the same data type. • If they are not, but are both arithmetic data types, the usual arithmetic conversions are applied to make their types the same. • If one is a pointer and the other is zero, the latter is taken as a null pointer of the same type as the former. • If one is a pointer to void and the other is a pointer to another type, the latter is converted to a pointer to void, and that is the resulting type. 30
  • 31. Conditional Operators (Cont…) #include<stdio.h> int main() { int num; int flag; printf("Enter the Number : "); scanf("%d",&num); flag = ((num%2==0)?1:0); printf ("Flag value : %d n", flag); return 0; } 31
  • 32. Type Cast Operator • You can convert the values from one type to another explicitly using the cast operator as follows: (type_name) expression • Refere Lecture 04 32
  • 33. sizeof Operator • Given that type is as the name of a basic data type, an enumerated data type (preceded by the keyword enum), a typedef-defined type, or is a derived data type; A is an expression; then the expression sizeof (type) has as its value the number of bytes needed to contain a value of the specified type; sizeof A  has as its value the number of bytes required to hold the result of the evaluation of A. 33
  • 34. sizeof Operator (Cont…) #include<stdio.h> int main() { int ivar = 100; char cvar = 'a'; float fvar = 10.10; double dvar = 18977670.10; printf("%dn", sizeof(ivar)); printf("%dn", sizeof(cvar)); printf("%dn", sizeof(fvar)); printf("%dn", sizeof(dvar)); return 0; } 34
  • 35. Comma Operator • The comma operator can be used to link the related expressions together. • A comma linked expression is evaluated from left to right and the value of the right most expression is the value of the combined expression. x = (a = 2, b = 4, a+b) • In this example, the expression is evaluated from left to right. • So at first, variable ‘a’ is assigned value 2, then variable ‘b’ is assigned value 4 and then value 6 is assigned to the variable ‘x’. • Comma operators are commonly used in for loops, while loops, while exchanging values. 35
  • 36. Comma Operator (Cont…) • Comma operator returns the value of the rightmost operand when multiple comma operators are used inside an expression. • Comma Operator Can acts as : ▫ Operator : In the Expression ▫ Separator : Declaring Variable , In Function Call Parameter List 36
  • 37. Comma Operator (Cont…) #include<stdio.h> int main() { int num1 = 1, num2 = 2; int res, x, a, b; x = (a = 2, b = 4, a+b); res = (num1, num2); printf("%dn", res); x = (a = 2, b = 4, a+b); printf("%dn", x); return 0; } 37
  • 38. C Arithmetic Expression • Arithmetic expression in C is a combination of variables, constants and operators written in a proper syntax. • C can easily handle any complex mathematical expressions but these mathematical expressions have to be written in a proper syntax. 38
  • 39. Operator Precedence & Associativity • Operator Precedence ▫ When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. ▫ For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has higher precedence than the binary + operator. ▫ The precedence of an operator is established by the definition of its associated grammar production. 39
  • 40. Operator Precedence & Associativity (Cont…) • Operator Associativity ▫ A higher precedence operator is evaluated before a lower precedence operator. ▫ If the precedence levels of operators are the same, then the order of evaluation depends on their associativity (or, grouping). 40
  • 41. Operator Precedence & Associativity (Cont…) • Example (1 > 2 + 3 && 4) This expression is equivalent to: ((1 > (2 + 3)) && 4) i.e, (2 + 3) executes first resulting into 5 then, first part of the expression (1 > 5) executes resulting into 0 (false) then, (0 && 4) executes resulting into 0 (false) 41
  • 42. Operator Precedence & Associativity (Cont…) (1 > 2 + 3 && 4) can be written as follows; =((1 > (2 + 3)) && 4) =((1>5) && 4) =(0 && 4) =0 42
  • 43. Summary of C Operators • These operators are listed in order of decreasing precedence. • Operators grouped together have the same precedence. 43
  • 44. Summary of C Operators (Cont…) 44 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
  • 45. Questions • Try this out: ▫ 250*2/4+1 ▫ 5%2*5/5 ▫ 2+300-200/2 ▫ 1 && 1 || 0 ▫ 1 || 1 +3-4 && 1 45
  • 46. Objective Re-cap • Now you should be able to: ▫ Define the terms operators, operands, operator precedence and associativity. ▫ Describe operators in C programming language. ▫ Practice the effect of different operators in C programming language. ▫ Justify evaluation of expressions in programming. ▫ Apply taught concepts for writing programs. 46
  • 47. References • Chapter 04, Appendix A, section 5 - Programming in C, 3rd Edition, Stephen G. Kochan 47
  • 48. Next: Program Control Structures – Decision Making & Branching 48