Computer ProgrammingChapter 3 Operators and Expressions
Computer ProgrammingChapter 3 Operators and Expressions
Bishon Lamichhane
Topics
3.1 Introduction to Operators and Expressions
3.2 Arithmetic Operator, Relational Operator and Logical Operators
3.3 Assignment, Increment and Decrement Operators
3.4 Conditional, Bitwise and Special Operators
3.5 Comma operator, sizeof operator
3.6 Evaluation and Type Conversion in Expressions
3.7 Operator Precedence and Associativity
Compiled by Bishon 2
Expression
ØAn expression is a combination of variables constants and operators
written according to the syntax of C language.
ØIn C every expression evaluates to a value i.e., every expression
results in some value of a certain type that can be assigned to a
variable.
ØSome examples of C expressions are shown in the table given below.
Compiled by Bishon 3
Algebraic Expression C Expression
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
3x2 + 2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c
Compiled by Bishon 4
ØAn expression is a formula in which operands are linked to each other
by the use of operators to compute a value.
Ø Each type of expression takes certain types of operands and uses a
specific set of operators. Evaluation of a particular expression
produces a specific value.
Compiled by Bishon 5
Evaluation of expressions:
Ø Expressions are evaluated using an assignment statement of the form
Variable = expression:
Ø Variable is any valid C variable name. When the statement is
encountered, the expression is evaluated first and then replaces the
previous value of the variable on the left hand side.
Compiled by Bishon 6
Compiled by Bishon 7
Operator
Compiled by Bishon 8
Unary operators
Ø Unary operators are the operators in C which are used to perform
certain operations on single operands.
Ø They are named unary because they work on only one operands.
Some of the unary operators are ++, --, -, !, etc.
Ø E.g., a++ (increments the value of a by 1).
Binary operators
Ø Binary operators are those operators that operate on two operands.
Examples are +, -, >, <, etc.
Compiled by Bishon 9
Ternary operator
Ø Ternary operator is that operator which acts upon three operands.
Ø Conditional operator (?:) is the only example of ternary operator.
Ø The conditional operator is similar to if-else statement as it follows
the same algorithm as of if-else statement. But the conditional
operator takes less space and helps to write the if-else statements in
the shortest way possible.
Compiled by Bishon 10
Based on utility and actions, C operators are classified as follows:
i.Arithmetic operators (+, –, *, /,%)
ii.Relational operators (>, <, <=, >=, = =, !=)
iii. Logical operators (&&, ||, !)
iv. Assignment operator (=)
v. Conditional operator (?:)
vi. Increment/decrement operators (++/– –)
vii. Bitwise Operator
viii.Comma Operator
ix. Sizeof Operator
x. Pointer operators(* and &)
xi. Member Selection Operator( . and à)
Compiled by Bishon 11
i. Arithmetic operators
Ø Arithmetic operators are those operators that perform different
arithmetic operations such as addition, subtraction, multiplication,
division etc.
Ø Examples are +, -, *, /, %. Modulo division operation is performed by
% operator (also known as remainder operator).
Ø It acts only upon integer operands. a%b gives the remainder when a is
divided by b, given that both a and b are integers.
Compiled by Bishon 12
Types of arithmetic operations
a. Integer Arithmetic
ØOperation involves only integer
ØYields always an integer value
ØFor example: if int x=5,y=17 then following are the some arithmetic
operations on x and y:
-(5)=-5 x + y=22
y / x=3 y % x=2
x - y=-12 x * y=85
x / y=0 x + ‘A’=70
Compiled by Bishon 13
4/5=0, -4/-5=0
ØBut -4/5 may be 0 or -1 (machine dependent)
ØIn remainder the sign of the result is always the sign of first operand
Ø-10%3=-1, -10%-3=-1,10%3=1
b. Mixed Mode Arithmetic
ØIf either of the operands is real then the resultant value is always a real value
ØIf float x=17.0; int y=5, then x/y = 3.400000, y/x = 0.294118
c. Real Arithmetic
ØInvolves only real operands
ØFinal result is approximation of the correct result
ØRemainder operator is not applicable
ØIf float a=10.5,b=-5.7 then a + b = 4.800000, a*c=-59.850000,b/a=0.542857
Compiled by Bishon 14
ii. Relational operators
Ø Those operators which are used to compare two similar operands, and
depending on their relation, take some actions are relational
operators.
Ø They compare their left hand side operand with their right hand side
operand for different relations.
Ø The value of a relational expression is either 1 (if the condition is
true) or 0 (if the condition is false). Different relational operators in C
are >, >=, <, <=, == (read equal to) and !=(read not equal to).
Ø For example, if a=5 and b=6, then the expression (a>b) results 0
(false).
Compiled by Bishon 15
iii. Logical operators
Ø Those operators which are used to compare or evaluate logical and
relational expressions are known as logical operators.
Ø The operands of these operators must be logical i.e., they must
produce either 1 (true) or 0 (false). The final result produced by these
operators is also either true or false. There are three logical operators
in C:
&& logical AND
| | logical OR
! logical NOT
Compiled by Bishon 16
Ø The logical AND (&&) produces true if each expression or operand
are true, otherwise it produces false. Similarly, logical OR ( | | )
produces true if at least one operand is true, otherwise it produces
false. The logical NOT(!) alters the operand, i.e. it produces true if
operand is false and vice versa.
Ø For example, if a=5, b=6, c=3, then the expression (a<b)&&(a>c)
results 1 (true).
Compiled by Bishon 17
iv. Assignment operator (=)
Ø It is a binary operator that assigns the result of an expression in right
hand side to a variable in left hand side.
Syntax: variable= expression;
Ø If a = 5, b = 6, then c = a + b means the value of a + b (i.e., 11) is
assigned to c. Also 5 is assigned to a and 6 is assigned to b.
Shorthand arithmetic assignment operator:
+ =, - =, * =, / =, % =
Ø They are used to write some expressions involving arithmetic and
assignment operators in shorthand form. For example,
Ø x=x+5 can be written as x+=5
Ø x=x-5 cane be written as x-=5, and so on.
Compiled by Bishon 18
v. Increment and decrement operator
Ø Increment operators are used to increase the value of the variable by
one and decrement operators are used to decrease the value of the
variable by one in C programs.
Ø Both increment and decrement operator are used on a single operand
or variable, so it is called as a unary operator. Unary operators are
having higher priority than the other operators it means unary
operators are executed before other operators.
Ø Note: Increment and decrement operators cannot be applied on
constant.
Ø x= 4++; // gives error, because 4 is constant
Compiled by Bishon 19
Type of increment operator:
i. Pre-increment
ii. Post-increment
1. pre-increment (++ variable):
ØIn pre-increment first increment the value of variable and then used
inside the expression (initialize into another variable).
Ø Syntax: ++ variable;
Example:
#include<stdio.h>
void main()
{
int x,i;
Compiled by Bishon 20
i=10;
x=++i;
printf("x: %d",x);
printf("i: %d",i);
}
Output:
x: 11
i: 11
Ø In above program first increase the value of i and then assign value of
i into expression.
Compiled by Bishon 21
2. post-increment (variable ++):
ØIn post-increment first value of variable is used in the expression
(initialize into another variable) and then increment the value of
variable.
Ø Syntax: variable ++;
Ø Example:
#include<stdio.h>
void main()
{
int x,i;
i=10;
x=i++;
Compiled by Bishon 22
printf("x: %d",x);
printf("i: %d",i);
}
Output:
x: 10
i: 11
Ø In above program first assign the value of i into expression then
increase value of i by 1. Similarly it can be done for decrement
operator.
Compiled by Bishon 23
Example:
#include<stdio.h>
void main( )
{
int x,a,b,c;
a=2;
b=4;
c=5;
x= a-- + b++ - ++c;
printf("x: %d",x);
}
Compiled by Bishon 24
Output: x: 0
[Explanation: x = 2 + 4 – 6 = 0]
vi. Conditional operator (?:)
ØIt is a ternary operator that is used to write conditional structures in
a single expression.
ØSyntax:
ØThe conditional operator is of the form:
Variable = Expression1 ? Expression2 : Expression3;
Compiled by Bishon 25
ØIt can be visualized into if-else statement as:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Ø Since the conditional operator ‘?:’ takes three operands to work,
hence they are also called ternary operators.
Compiled by Bishon 26
Working:
Ø Here, Expression1 is the condition to be evaluated.
Ø If the condition (Expression1) is true, then Expression2 will be
executed and the result will be returned.
Ø Otherwise, if the condition (Expression1) is false, then Expression3
will be executed and the result will be returned.
Compiled by Bishon 27
vii. Bitwise Operator
ØOperates on each bit of data
ØRequired in bit level programming
ØUsed for complementing or shifting bits to the left or right
ØNot applicable to real data i.e float and double
Compiled by Bishon 28
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift Left
>> Shift Right
~ Bitwise Complement
Compiled by Bishon 29
1. Bitwise AND Operator
ØThe output of bitwise AND is 1 if the corresponding bits of two
operands is 1. If either bit of an operand is 0, the result of
corresponding bit is evaluated to 0.
ØIn C Programming, the bitwise AND operator is denoted by &.
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
00001000 = 8 (In decimal)
Compiled by Bishon 30
2. Bitwise OR Operator
ØThe output of bitwise OR is 1 if at least one corresponding bit of two
operands is 1.
ØIn C Programming, bitwise OR operator is denoted by |.
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
00011101 = 29 (In decimal)
Compiled by Bishon 31
3. Bitwise XOR (exclusive OR) Operator
ØThe result of bitwise XOR operator is 1 if the corresponding bits of
two operands are opposite.
ØIt is denoted by ^.
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
^ 00011001
00010101 = 21 (In decimal)
Compiled by Bishon 32
4. Bitwise Complement Operator
ØBitwise complement operator is a unary operator (works on only one
operand).
ØIt changes 1 to 0 and 0 to 1.
ØIt is denoted by ~.
Example:
35 = 00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
11011100 = -(36) (In decimal)
Compiled by Bishon 33
5. Right Shift Operator
ØRight shift operator shifts all bits towards right by certain number of
specified bits. It is denoted by >>.
Example:
212 = 0000000011010100 (In binary)
212 >> 0 = 0000000011010100 = 212 (No Shift)
212 >> 1 = 0000000001101010 =106
212 >> 2 = 0000000000110101 = 53 (In binary) [Right shift by two bits]
212 >> 3 = 0000000000011010 = 26
212 >> 7 = 0000000000000001 =1(In binary)
212 >> 8 = 0000000000000000=0
Compiled by Bishon 34
6. Left Shift Operator
ØLeft shift operator shifts all bits towards left by a certain number of
specified bits.
ØThe bit positions that have been vacated by the left shift operator are filled
with 0.
ØThe symbol of the left shift operator is <<.
Example:
12 = 0000000000001100 (In binary)
12<<0 = 0000000000001100 (Shift by 0)
12<<1 = 0000000000011000 = 24[Left shift by one bit]
12<<2 = 0000000000110000 = 48[Left shift by two bits]
12<<3 = 0000000001100000 = 96[Left shift by three bits]
12<<4 = 0000000011000000 = 192
Compiled by Bishon 35
viii. Comma Operator
ØIn C programming, the comma operator (",") is used to separate
multiple expressions.
ØIt allows us to evaluate multiple expressions sequentially and return
the value of the last expression.
ØEach expression is evaluated from left to right, and the comma
operator guarantees the order of evaluation.
Compiled by Bishon 36
ØThe syntax of the comma operator is as follows:
expression1, expression2, ..., expressionN
Here's how the comma operator works:
ØEvaluate expression1.
ØDiscard the result of expression1.
ØEvaluate expression2.
ØDiscard the result of expression2.
...
ØEvaluate expressionN.
ØReturn the value of expressionN.
Compiled by Bishon 37
Usage of Comma Operator
1. In Variable declaration
int a,b,c,d;
2. In a for loop
for (i = 0, j = 10; i < 5; i++, j--)
{
// Loop body
}
3. In a function call
result = func(expression1, expression2, expression3);
4. As part of a larger expression:
int x = (a = 5, b = 10, a + b); // x will be 15
Compiled by Bishon 38
ix. Sizeof Operator
ØIn C programming, the sizeof operator is used to determine the size in
bytes of a data type, a variable or an expression.
ØIt allows us to find out how much memory a particular data type,
variable or an expression occupies in the computer's memory.
ØThe syntax of the sizeof operator is as follows:
sizeof(type)
sizeof(expression)
ØHere, type can be any valid C data type, such as int, float, char,
double, user-defined structures, or pointers. Alternatively, we can use
sizeof with an expression, and it will give us the size of the
expression's result in bytes.
Compiled by Bishon 39
Example:
1.Size of a data type:
#include <stdio.h>
int main()
{
printf("Size of int: %u bytes\n", sizeof(int));
printf("Size of char: %u bytes\n", sizeof(char));
printf("Size of double: %u bytes\n", sizeof(double));
return 0;
}
Compiled by Bishon 40
2. Size of Variable
#include <stdio.h>
int main()
{
int x = 42;
printf("Size of x: %u bytes\n", sizeof(x));
return 0;
}
Compiled by Bishon 41
x. Pointer operators(* and &)
xi. Member Selection Operator( . and à)
Compiled by Bishon 42
Operator Precedence and Associativity
Precedence of Operators
ØIf more than one operators are involved in an expression then, C
language has predefined rule of priority of operators. This rule of
priority of operators is called operator precedence.
ØIn C, precedence of arithmetic operators(*, %, /, +, -) is higher than
relational operators(==,!=,>,<,>=,<=) and precedence of relational
operator is higher than logical operators(&&, || and !).
ØConsider an expression, (a > b + c && d) .
ØThis expression is equivalent to: ((a>(b+c))&&d) i.e., (b+c) executes
first then, (a>(b+c)) executes then, (a>(b+c))&&d) executes.
Compiled by Bishon 43
Associativity of Operators
ØAssociativity indicates in which order two operators of same
precedence (priority) executes. Let’s consider an expression,
a==b!=c
ØHere, operators == and != have same precedence.
ØThe associativity of both == and != is left to right, i.e, the expression
in left is executed first and execution take pale towards right.
ØThus, a= =b!=c equivalent to :(a= =b)!=c.
Compiled by Bishon 44
Operator Description Associativity Precedence
( ) Function call Left to right 1
[ ] Array element reference
+ Unary plus
– Unary minus Right to left 2
++ Increment
–– Decrement
! Logical negation
* Pointer reference (indirection)
& Address
sizeof Size of an object
(type) Type cast (conversion)Compiled by Bishon 45
Operator Description Associativity Precedence
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
– Subtraction
<< Left shift Left to right 5
>> Right shift
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
Compiled by Bishon 46
Operator Description Associativity Precedence
== Equality Left to right 7
!= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional expression Right to left 13
Compiled by Bishon 47
Operator Description Associativity Precedence
= Assignment operators Right to left 14
*=/=%=
+=–=&=
^=|=
<< = >> =
, Comma operator Left to right 15
Compiled by Bishon 48
Type casting
ØType casting in C is a technique used to convert a value from one data
type to another.
ØIt allows us to change the interpretation of data without changing its
actual value.
ØType casting is useful in situations where we want to perform
operations that involve different data types or when we need to store a
value of one data type into a variable of another data type.
ØThere are two type of casting in C:
i. Implicit type conversion
ii. Explicit type conversion
Compiled by Bishon 49
Implicit Type Conversion
Ø C performs automatic conversions of type in order to evaluate the
expression. This is called implicit type conversion.
Ø For example, if we have an integer data type value and a double data
type value in an expression then C will automatically convert integer
type value to double in order to evaluate the expression.
Ø Remember the following hierarchy ladder of implicit type
conversion.
Compiled by Bishon 50
!"#$%&"'(!)
&"'(!)
*!"+,
'#-.$#)&%!"#$%.#,
/"#2)1-."#
0.)1+1/03 !"#$%.#,
'#-.$#)&%.#,
.#,
/0+1 -0"1,
Compiled by Bishon 51
ØIf we downgrade from a higher data type to a lower data type then it
causes loss of bits.
ØFor example, moving from double to float causes rounding of digits.
Downgrading from float to int causes truncation of the fractional part.
Compiled by Bishon 52
Explicit Type Conversion (Type Casting)
Ø In explicit type conversion, we decide into what type we want to
convert the expression.
Ø Syntax of explicit type conversion:
(type) expression
ØWhere, type is any of the type we want to convert the expression into.
Compiled by Bishon 53
In the following example, we are converting floating point numbers into
integer.
#include <stdio.h>
int main()
{
float x = 24.5, y = 7.2;
int result = (int) x / (int) y; //converting float to int
printf("Result = %d\n", result);
return 0;
}
Compiled by Bishon 54
ØIn the above code (int) x converts the value 24.5 into 24 and (int) y
converts the value 7.2 into 7 so, we get 24/7 i.e., 3 as result because
result is of type int and hence the decimal part is truncated.
Compiled by Bishon 55
Program Statement
ØA program statement, also known as a code statement or simply a
statement, is a fundamental unit of code in a computer program.
ØIt represents a single action or operation that the computer should
execute.
ØA program consists of a sequence of statements, and each statement
serves a specific purpose, such as assigning values to variables,
performing calculations, making decisions, or controlling the flow of
execution.
ØIn C, statements are terminated by a semicolon (;) to indicate the end
of the statement. The semicolon acts as a separator, allowing the
compiler or interpreter to distinguish one statement from another.
Compiled by Bishon 56
Assignment Statement
ØAn assignment statement assigns a value to a variable. It has the form:
variable = expression;
int x;
x = 10; // Assign the value 10 to the variable 'x'
Arithmetic Statement
ØAn arithmetic statement performs a mathematical operation and may
involve variables and constants.
int a = 5, b = 3, result;
result = a + b; // Perform addition and store the result in 'result'
Conditional Statement
ØA conditional statement makes a decision based on a condition and
controls the flow of execution.Compiled by Bishon 57
int num = 7;
if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is non-positive.\n");
}
Loop Statement:
ØA loop statement allows repeated execution of a block of code based
on a condition.
int i;
for (i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
} Compiled by Bishon 58
Function Call Statement
ØA function call statement invokes a function to perform a specific
task.
sum = add(5, 3); // Call the 'add' function with arguments 5 and 3
Input/Output Statement
ØAn input/output statement reads input from the user or displays output
to the screen.
int age;
printf("Please enter your age: ");
scanf("%d", &age); // Read user input and store it in the 'age' variable
Compiled by Bishon 59
Chapter 3 Ends Here
Compiled by Bishon 60