0% found this document useful (0 votes)
16 views

Part 4-Operators and Expressions-15.03.2024

The document provides an overview of operators in programming, specifically in the C language, categorizing them into unary and binary operators, with detailed explanations of arithmetic, relational, logical, bitwise, and special operators. It covers the functionality of various operators, including increment and decrement, sizeof, addressof, and conditional operators, along with examples of their usage. Additionally, it discusses expressions, their types, and how they are formed using operands and operators.

Uploaded by

aqib943259
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Part 4-Operators and Expressions-15.03.2024

The document provides an overview of operators in programming, specifically in the C language, categorizing them into unary and binary operators, with detailed explanations of arithmetic, relational, logical, bitwise, and special operators. It covers the functionality of various operators, including increment and decrement, sizeof, addressof, and conditional operators, along with examples of their usage. Additionally, it discusses expressions, their types, and how they are formed using operands and operators.

Uploaded by

aqib943259
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Course Name: Programming for Problem Solving

Course Code: ES-CS201

Arithmetic Expressions and Precedence


OPERATORS
Operators are the foundation of any programming language. The functionality of any
programming language is incomplete without the use of operators.

Operators, generally, are of two types:


o Unary Operators – operators that operate on a single operand. The unary operators
are prefixed with their operands.
For example, –x, here unary minus '–' operator precedes by its operand x (supposed to
hold a numeric value), and negates its value, i.e., changes its sign.
o Binary Operators – operators that operate with two operands. The binary operators
are embedded between their operands.
For example, a+b, here binary plus '+' operator appears between its operands a and b
(both supposed to hold numeric values), and adds the value of variable b to that of a.

The C language’s rich set of operators is one of its distinguished features. These operators
can be enumerated in following categories:

 Arithmetic Operators ( +, , *, /, % )
 Relational Operators ( <, <=, >, >=, ==, != )
 Logical Operators ( !, &&, || )
 Bit-wise Operators ( ~, >>, <<, &, | , ^)
 Special Operators

o Increment & Decrement Operators ( ++, - - )


o The sizeof Operator
o The addressof Operator ( & )
o Indirection/de-reference Operator ( * )
o Ternary/Conditional Operator ( ? : )

Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.

1
Binary Arithmetic Operators
Operator Symbol Form Operation
Addition + x+y Adds value of y to value of x.
Subtraction – x–y Subtracts value of y from value of x.
Multiplication * x*y Multiplies value of x by value of y.
Division / x/y Divides value of x by value of y.
Modulus % x%y Divides value of x by value of y and gives remainder.

Integer Arithmetic

When both the operands are integers, the operations will be called integer arithmetic and
will always yield an integer value.

Consider the following statements


int x = 13, y = 5;
then we have the following results:
x – y = 8
x + y = 18
x * y = 65
x / y = 2 (decimal part truncated)
x % y = 3 (remainder of division)

Real Arithmetic

 When both the operands are real numbers, the operations will be called real
arithmetic and will always yield a real value.

 Since real numbers (floating-point values) are rounded to permissible number of


significant digits, result of arithmetic operations is an approximate value of correct
result.

That is
6.0 / 7.0 = 0.857143
-1.0 / 3.0 = -0.333333
3.0 / -2.0 = -1.500000

The modulus operation cannot be used with real operands.

Mixed-mode Arithmetic

 When one of the operands is real and the other is integer, the operations will be
called mixed-mode arithmetic and will always yield a real value.

 The integer operand is converted into real operand and then real arithmetic is
performed, resulting in a real value.

pg. 2
That is
6 / 7.0  6.0 / 7.0 = 0.857143
-1.0 / 3  -1.0 / 3.0 = -0.333333

Note that
15 / 10.0 = 1.5
15.0 / 10 = 1.5

where as
15 / 10 = 1

Relational (Comparison) Operators


 These operators are used to compare values of the operands that must be
compatible, in order to facilitate decision-making.

 If the comparison succeeds, they return a value 1 (equivalent to Boolean value


true) and if comparison fails then they return a value 0 (equivalent to Boolean
value false).

Relational (Comparison) Operators

Operator Symbol Form Meaning


Greater than > x>y Return True if x is greater than y.
Return True if x is greater than or
Greater than or equal to >= x >= y
equal to y.
Less than < x<y Return True if x is less than y.
Return True if x is less than or equal
Less than or equal to <= x <= y
to y.
Equal to == x == y Return True if x and y are equal.
Not equal to != x != y Return True if x and y are not equal.

Logical Operators
These operators are used to form compound conditions by joining two or more simple
conditions formed using relational operators.

Logical Operators
Operator Symbol Form Meaning
Logical AND && x && y Return True if both the operands are True.
Logical OR || x || y Return True if either of the operands is True.
Return True if operand is false, and False if
Logical NOT ! !x
operand True (complements the operand).

pg. 3
Bitwise Operators

Bitwise operators act on operands as if they were string of binary digits. It operates bit by
bit. Note that these operators are used with integral operands only.

To demonstrate the working of bitwise operators, let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary), assuming that 8 bits are used to represent an integer number.

Bitwise Operators

Operator Symbol Form Meaning Example


x = 0000 1010 (10)
Return 1 if corresponding bits
Bitwise AND & x&y y = 0000 0100 (4)
are 1 else 0. x & y = 0000 0000 (0)

Return 1 if either or both of x = 0000 1011 (11)


Bitwise OR | x|y corresponding bits are 1 else y = 0000 0101 (5)
0. x | y = 0000 1111 (15)

x = 0000 1011 (11)


Return 1 if corresponding bits
Bitwise XOR ^ x^y y = 0000 0101 (5)
are not equal. x ^ y = 0000 1110 (14)
x = 0000 1011 (11)
Bitwise NOT ~ ~x Inverts 1 to 0 and 0 to 1 ~x = 1111 0100 (-12)

Shifts the bits of left operand


to right by number of bits
specified by the right
operand. The right most bit is
Bitwise right shifted out after each shift, x = 0000 1011 (11)
>> x >> y while the left most bit is x >> 1 = 0000 0101 (5)
shift
restored.
Note: Each right shift by 1-bit
is equivalent to integral
division by 2.
Shifts the bits of left operand
to left by number of bits
specified by the right
operand. The left most bit is
Bitwise left shifted out after each shift, x = 0000 1011 (11)
<< x << y while the right most bit is x << 1 = 0001 0110 (22)
shift
filled with 0.
Note: Each left shift by 1-bit is
equivalent to multiplication
by 2.

Increment & Decrement Operators


The C language supports two very useful operators

Increment operator (++) and Decrement operator (--). These operators can be used with
all basic data types. The increment operator adds 1 to the operand, while decrement
operator subtracts 1 from the operand.

pg. 4
Both operators are unary operators and can be used in the prefix as well as postfix
notation as shown below:

++k; or k++;
--k; or k--;

Here, ++k (as well as k++) is equivalent to k = k + 1 or k += 1, and --k (as well as k--)
is equivalent to k = k - 1 or k -= 1.

These operators are most frequently used in while and for loops as control variables.

While ++k or k++ means the same thing when they form statements independently, they
behave differently when they are used as part of other expressions.
Consider the following statements
int y, k = 5;
y = ++k;

In this case, first the value of k is incremented and then assigned to y, and hence y and k
will have same value as 6. Thus, the above statements are equivalent to following
statements
int y, k = 5;
++k;
y = k;

However, if we write the above statements as


int y, k = 5;
y = k++;

then first the current value of k (value 5) is assigned to y and then the value of k is
incremented, and hence y will have value 5 while k will have value as 6.

Thus, the above statements are equivalent to following statements


int y, k = 5; int y, k = 5;
y = k; or y = k;
++k; k++;

The sizeof Operator


The sizeof operator returns the size, in bytes, of the given operand. The syntax of sizeof
operator is
sizeof( exp )

where exp represents a data type (built-in or user-defined), a literal/constant or a variable.


For example
sizeof( float )

returns value 4.

pg. 5
Use of sizeof Operator

sizeof Operator used as Returns Justification


sizeof(12) 2
Integer constant by default belong to data type int, and
size for int is 2 on Turbo C/C++ and 4 on Dev C++.
sizeof('a') 1 Size of Character constant is 1.

sizeof(int) 2
Size of data type int is 2 on Turbo C/C++ and 4 on Dev
C++.
sizeof(125.25) 8 Real constant by default belong to data type double.

sizeof(125.25F) 4 Real constant is of data type float, and size for float is 4.
double x;
8 Variable x is of type double, and size for double is 8.
sizeof(x);

The addressof Operator


 Character '&' when prefixed with a variable returns the address of the memory
locations, hence its name addressof operator.

 It is used in the scanf() function and to initialize the pointers. The use of addressof
(&) operator is demonstrated in

Character '*' when prefixed with a pointer variable returns the value stored in a memory
location whose address is held in pointer variable. That is, value is accessed through pointer
variable indirectly, hence its name indirection operator.

Consider following statements

int y = 10, x;
int *py;
py = &y;
x = *py;

The expression "*py" returns the values at address which held in pointer variable py, i.e.,
value of variable y which is 10, gets assigned to variable x.
Use of addressof (&) Operators

addressof (&) Operator used as Task Performed


First statement declares and defines variable y of type
int. It also initializes it with value 10.
int y = 10; Second statement declares and defines a pointer
int *py; variable py that can hold an address of a memory
py = &y;
location reserved for storing value of type int.
Third statement assigns the address of variable y to
pointer variable py.
First statement declares and defines two variable x and
y of type int.
int x, y;
scanf("%d %d", &x, &y); Second statement takes two integer values as input
from the keyboard and stores those values at addresses

pg. 6
of variable x and y, respectively.

Conditional/Ternary Operator
Consider the following segment,
if ( a > b ) then
set big = a
else
set big = b
endif

 This segments assigns the maximum of the values of a and b to big. It is clear that
the value assigned to variable big will depend on the outcome of the test condition
"a > b".

 Such expressions are known as conditional expressions, and can be written using
conditional operator. The syntax of using ternary operator is
exp1 ? exp2 : exp3;

where exp1, exp2, exp3 are expressions.

The expression exp1 is evaluated first. If it is non-zero (true), then the expression exp2 is
evaluated, and that is the value of the conditional expression; otherwise expression exp3 is
evaluated, and that is the value of the conditional expression. Note that only one of the
expression exp2 and exp3 is evaluated.

Thus, the above pseudocode segment using conditional operator can be written as
big = ( a > b ) ? a : b;

Assignment Operators

Assignment operators are used to assign values to variables. For example,

a = 5

Here '=' is a simple assignment operator that assigns the value 5 to the variable a. It can
also be used to assign value of another variable or an expression.

There are various compound operators in C like


a += 5

that adds to the variable and later assigns the same. It is equivalent to

a = a + 5

pg. 7
Operators of type '+=' are also called shorthand assignment operators.

Assignment operator

Operator Example Equivalent to Operator Example Equivalent to

= x = 5 x = 5 &= x &= 5 x = x & 5

+= x += 5 x = x + 5 |= x |= 5 x = x | 5

-= x -= 5 x = x - 5 ^= x ^= 5 x = x ^ 5

*= x *= 5 x = x * 5 >>= x >>= 5 x = x >> 5

/= x /= 5 x = x / 5 <<= x <<= 5 x = x << 5

%= x %= 5 x = x % 5

EXPRESSIONS
An expression is a formula consisting of one or more operands and zero or more operators
linked together to compute a value. An operand may be a function reference, a variable, an
array element or a constant.

For example, in the expression


a + b

plus character ‘+’ is an operator and a and b are operands.

There are four types of expressions in C. These are

1. Arithmetic expressions
2. Relational expressions
3. Logical expressions
4. Conditional expressions

Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of every expression produces a value of specific type. Expressions
are not statements, but may be components of statements.
For example, consider the line
x = 2.0/3.0 + a * b;

pg. 8
Arithmetic Expressions

Some sample arithmetic expressions

Mathematical/Algebraic Expressions The C Arithmetic Expressions


ab (a+b)/2
2
b a+b/c+d
a d
c
ab (a*b)/(cd*d)+d
d
c  d2
a
1 1+a/(b+1/c)
1
b
c
a
e a/((c+b)/d)e
cb
d
a*x*x+b*x+c
ax2  bx  c
1 2
ut  at u*t+0.5*a*t*t
2
 v2 
m a  h   m*(a*h+(v*v)/2)
 2 

While converting mathematical/algebraic expressions into C arithmetic expressions,


parentheses can be used to control associativity and the order in which operators are
evaluated. If parentheses are present in an expression, then the expression within the
parentheses is evaluated first and within the parentheses the implicit precedence is
observed. If there is nesting of parentheses (parentheses inside parentheses), then the inner
most parentheses are evaluated first.

Evaluation of Expressions
Precedence
The concept of precedence is well defined in the subject of mathematics.
The rule BODMAS – Brackets, Of, Division, Multiplication, Addition, and
Subtraction.

In algebra, division and multiplication is performed before addition and subtraction.

The following is a simple example of precedence:


5 + 3 * 4

This expression consists of one addition and one multiplication operator. As you know
from the knowledge of algebra, multiplication has higher precedence than addition,
multiplication is performed before addition.

pg. 9
Therefore, the expression will be evaluated as
( 5 + ( 3 * 4 ) )  ( 5 + 12 )  17

giving 17 as the value of the entire expression.


To illustrate the way arithmetic expression are evaluated, consider the following
expression
5 * 4 / ( 1 + 5 * 2 / 3 + 6 ) + 8 * ( 7 / 4 )

This expression is evaluated as demonstrated in Table depicted below:

Illustration of evaluation of arithmetic expression

Operation by Operation
Description of Each Operation
Evaluation of Expression

5 * 4 / ( 1 + 5 * 2 / 3 + 6 ) + 8 * ( 7 / 4 ) Given expression

5 * 4 / ( 1 + 10 / 3 + 6 ) + 8 * ( 7 / 4 ) 5 is multiplied by 2, giving10

5 * 4 / ( 1 + 3 + 6 ) + 8 * ( 7 / 4 ) 10 is divided by 3 using integral division, giving


3

5 * 4 / ( 4 + 6 ) + 8 * ( 7 / 4 ) 3 is added to 1, giving 4

5 * 4 / 10 + 8 * ( 7 / 4 ) 6 is added to 4, giving 10

5 * 4 / 10 + 8 * 1 7 is divided by 4 using integral division, giving 1

20 / 10 + 8 * 1 5 is multiplied by 4, giving 20

2 + 8 * 1 20 is divided by 10 using integral division,


giving 2

2 + 8 8 is multiplied by 1, giving 8

8 is added to 2, giving 10, which is the final


10
value of the expression.

2.4 PRECEDENCE AND ASSOCIATIVITY


Precedence is used to determine the order in which different operators are evaluated in an
expression.

Associativity is used to determine the order in which different operators with same
precedence are evaluated in an expression.

Precedence is applied before associativity to determine the order in which expressions are
evaluated. Associativity is applied later, if necessary.

pg. 10
Associativity
 Associativity is applied when more than one operator of same precedence is used
in an expression.
 Associativity can be left-to-right or right-to-left.
 Left-to-right associativity evaluates the expression by starting on the left and
moving to the right whereas the right-to-left associativity evaluates the expression
by starting on the right and moving to the left.
The following is a simple example of associativity:
2 + 5 + 7

This expression consists of two addition operators. Here the associativity determines how
the sub expressions are grouped together. Since the addition operator has left-to-right
associativity, the expression will be grouped as
( ( 2 + 5 ) + 7 )  ( 7 + 7 )  14

giving 14 as the value of the entire expression.

pg. 11
Precedence and Associativity of Operators

Precedence
Operator Description Associativity
Level (Rank)
() Function call
[] Array element reference
> Structure operator used with pointer to a structure 1 Left-to-right
. Structure operator used with structure variable
! Logical NOT operator
~ 1's complement
++ Increment
 Decrement
+ Unary plus 2 Right-to-left
 Unary minus
* Pointer reference (indirection)
& Address of
(type) Type cast
sizeof Size of an operand
* Multiplication
/ Division 3 Left-to-right
% Modulus (remainder)
+ Addition
4 Left-to-right
 Subtraction
<< Left shift
5 Left-to-right
>> Right shift
< Less than
<= Less than or equal to
6 Left-to-right
> Greater than
>= Greater than or equal to
== Equal to
7 Left-to-right
!= Not equal to
& Bitwise AND 8 Left-to-right
^ Bitwise exclusive OR 9 Left-to-right
| Bitwise inclusive OR 10 Left-to-right
&& Logical AND 11 Left-to-right
|| Logical OR 12 Left-to-right
?: Condition (ternary) 13 Right-to-left
= +=
= *=
/= %=
Assignment operators 14 Right-to-left
&= ^=
!= <<=
>>=

pg. 12
EXAMPLES

Example 1: Swap values of two variables ‘a’ & ‘b’ using third variable ‘t’.

Solution:
Statement No. a b t
int a=10,b=20,t; /* 1 */ 1 10 20 ?
t = a; /* 2 */ 2 10 20 10
a = b; /* 3 */ 3 20 20 10
b = t; /* 4 */ 4 10 20 10

The last three lines of the code can also be written in C as


t = a, a = b, b = t;

Example 2: Swap value of two variables ‘a’ & ‘b’ without using third variable and using
arithmetic addition (+) and subtraction () operations only.
Solution:

int a=10,b=20; /* 1 */ Statement No. a b


a = a + b; /* 2 */ 1 10 20
b = a  b; /* 3 */ 2 30 20
3 30 10
a = a  b; /* 4 */
4 20 10
This task can also be implemented using following single statement:
a = ( a + b )  ( b = a );

Example 3: Swap value of two variables ‘a’ & ‘b’ without using third variable and using
arithmetic multiplication (*) and division (/) operations only.
Solution:
Statement No. a b
int a=10,b=20; /* 1 */ 1 10 20
a = a * b; /* 2 */
2 200 20
b = a / b; /* 3 */ 3 200 10
a = a / b; /* 4 */ 4 20 10
This task can also be implemented using following single statement:
a = ( a * b ) / ( b = a );

pg. 13
Example 4: To find the largest of three numbers among a, b, and c.
Solution:
int a = 10,b = 30,c = 25, big;

big = (a>b)?((a>c)?a:c)):((b>c)?b:c));

Here, if a is greater than b, expression ((a>c)?a:c) is evaluated; otherwise expression


((b>c)?b:c).
Expression ((a>c)?a:c) will return a if a is greater than c else returns c.
Expression ((b>c)?b:c) will return b if b is greater than c else returns c.

Example 5: Write appropriate statements to find the sum of the right-most digit and left-
most digit of a 4-digit number stored in n.
Solution:
left_most_digit = n / 1000;
right_most_digit = n % 1000;
sum = left_most_digit + right_most_digit;

Example 6: Write appropriate statements to convert temperature in Celsius scale into


Fahrenheit scale.
Solution:
The relationship between temperatures in Celsius scale and Fahrenheit scale is
C F  32 180
  F  32  C  F  1.8C  32
100 180 100

float c, f;
f = 1.8 * C + 32;

pg. 14
C PROGRAM FOR PRACTICALS
1. Write a program to find simple and compound interest.

Solution: The formulae to compute simple and the compound interest are

p  r  t , and
Simple interest 
100
 r  
t

Compound interest = p 1    1


 100  

where p is the principle amount, r is the rate of interest per annum, and t is the time of
deposit in years.

Program 1
/* program to compute simple and compound interest */
#include <stdio.h>
#include <math.h>
int main()
{
float p, r, si, ci;
int t;
printf("\nEnter principle amount : ");
scanf("%f", &p);
printf("Enter rate of interest : ");
scanf("%f", &r);
printf("Enter principle amount : ");
scanf("%d", &t);
si = (p*r*t)/100;
ci = p*(pow(1+r/100,t)-1);
printf("\nsimple interest = Rs. %.2f", si);

printf("\ncompound interest = Rs. %.2f", ci);


return 0;
}

pg. 15
Result
Enter principle amount : 1000
Enter rate of interest : 5
Enter principle amount : 4

Simple interest = Rs. 200.00


Compound interest = Rs. 215.51

2. Write a program to find the area of a triangle whose measure of three sides is
given as a, b, and c, respectively. The values of a, b, and c must satisfy the
condition that
a + b > c and b + c > a and c + a > b

Solution: The formulae to compute area of triangle is

abc
s
2
area  s ( s  a)(s  b)(s  c)

Program 2
/* program to compute area of a triangle whose sides are
given */
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, s, area;
printf("\nEnter value for a : ");
scanf("%f", &a);
printf("Enter value for b : ");
scanf("%f", &b);
printf("Enter value for c : ");
scanf("%f", &c);
s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("\nArea of triangle = %.2f Sq. Units", area);
return 0;
}

pg. 16
Result

Enter value for a : 5


Enter value for b : 7
Enter value for c : 6

Area of triangle = 14.70 Sq. Units

pg. 17

You might also like