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

Unit 2 Notes

Uploaded by

sanskarkale24
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Unit 2 Notes

Uploaded by

sanskarkale24
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit 2

Operators and Expressions


What is a C Operator?

An operator in C can be defined as the symbol that helps us to perform some


specific mathematical, relational, bitwise, conditional, or logical computations
on values and variables. The values and variables used with operators are
called operands. So we can say that the operators are the symbols that perform
operations on operands.

For example,
c = a + b;

Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are
operands. The addition operator tells the compiler to add both of the operands
‘a’ and ‘b’.

Types of Operators in C

C language provides a wide range of operators that can be classified into 6


types based on their functionality:
1. Arithmetic Operators
1. Relational Operators
1. Logical Operators
1. Bitwise Operators
1. Assignment Operators
1. Other Operators
2.1 Arithmetic operators
Arithmetic operators are used to perform common mathematical operations

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

Integer Arithmetic
When both the operands are integer.
a-b=10
a+b=18
Real Arithmetic
When both the operands are real.
x=6.0/7.0
y=1.0/3.0
Mixed Mode Arithmetic
When one operand is real and another is integer.
x=15/10.0
y=15/10
#include <stdio.h>
int main()
{
int a = 10, b = 4, res;
// printing a and b
printf("a is %d and b is %d\n", a, b);
res = a + b; // addition
printf("a + b is %d\n", res);
res = a - b; // subtraction
printf("a - b is %d\n", res);
res = a * b; // multiplication
printf("a * b is %d\n", res);
res = a / b; // division
printf("a / b is %d\n", res);
res = a % b; // modulus
printf("a %% b is %d\n", res);
return 0;
}
2.2 Relational operators
relational operators are the symbols that are used for comparison between
two values to understand the type of relationship a pair of numbers shares.
The result that we get after the relational operation is a boolean value, that tells
whether the comparison is true or false.
Relational operators are mainly used in conditional statements and loops to
check the conditions in C programming.
Types of C Relational Operators
There are a total of 6 relational operators in C language. There are:
1. Equal to operator (==)
The C equal to operator (==) is a relational operator that is used to check
whether the two given operands are equal or not.
 Equal to operator is a binary operator hence it requires two operands to
perform the comparison.
 If the two values are equal, it returns true. Otherwise, it returns false.
 It does not work for strings or arrays.
Syntax
operand1 == operand2
For example, 5==5 will return true.
2. Not equal to operator (!=)
The C not equal (==) to operator is another relational operator used for
checking whether the two given operands are equal or not.
 It is also a binary operator, requiring two operands to perform the
comparison.
 It is the exact boolean complement of the ‘==’ operator which returns true
if the two values are not equal, false otherwise.
Syntax
operand1 != operand2
For example, 5!=5 will return false.
3. Greater than operator (>)
The greater than operator is a relational operator in C that checks whether the
first operand is greater than the second operand or not.
 It is a binary operator.
 If the operand first is greater than the operand2, it returns true. Otherwise,
it returns false.
 This operator is used to make decisions or create conditions based on the
relative magnitude of two values.
Syntax
operand1 > operand2
For example, 6>5 will return true.
4. Less than operator (<)
The less than operator is a relational operator in C that checks whether the first
operand is lesser than the second operand.
 It is a binary operator.
 If the operand first is less than the operand2, it returns true. Otherwise, it
returns false.
 This operator is also used to make decisions or create conditions based on
the relative magnitude of two values.
Syntax
operand1 < operand2
For example, 6<5 will return false.
5. Greater than or equal to operator (>=)
The greater than or equal to the operator is a relational operator in C that
checks whether the first operand is greater than or equal to the second operand.
 It is a binary operator.
 If the operand first is greater than or equal to the operand2, it returns true.
Otherwise, it returns false.
Syntax
operand1 >= operand2
For example, 5>=5 will return true.
6. Less than or equal to the the operator (<=)
The less than or equal to the operator is a relational operator in C that checks
whether the first operand is less than or equal to the second operand.
 It is a binary operator.
 If the operand first is greater than or equal to the operand2, it returns true.
Otherwise, it returns false.
Syntax
operand1 <= operand2
For example, 5<=5 will also return true.

#include <stdio.h>

int main()

int a = 10, b = 4;
// greater than example

if (a > b)

printf("a is greater than b\n");

else

printf("a is less than or equal to b\n");

// greater than equal to

if (a >= b)

printf("a is greater than or equal to b\n");

else

printf("a is lesser than b\n");

// less than example

if (a < b)

printf("a is less than b\n");

else

printf("a is greater than or equal to b\n");

// lesser than equal to

if (a <= b)

printf("a is lesser than or equal to b\n");

else

printf("a is greater than b\n");

// equal to

if (a == b)

printf("a is equal to b\n");


else

printf("a and b are not equal\n");

// not equal to

if (a != b)

printf("a is not equal to b\n");

else

printf("a is equal b\n");

return 0;

2.3 Logical operators


Logical operators in C are used to combine multiple conditions/constraints.
Logical Operators returns either 0 or 1, it depends on whether the expression
result is true or false. In C programming for decision-making, we use logical
operators.
We have 3 logical operators in the C language:
 Logical AND ( && )
 Logical OR ( || )
 Logical NOT ( ! )

1. Logical AND Operator ( && )

If both operands are non-zero then the condition becomes true. Otherwise, the
result has a value of 0. The return type of the result is int. Below is the truth
table for the logical AND operator.

X && Y
X Y

1 1 1

1 0 0
0 1 0

0 0 0

Syntax (operand_1 && operand_2)


#include <stdio.h>
int main()
{
int a = 10, b = 20;
if (a > 0 && b > 20) {
printf("Both values are greater than 0\n");
}
else {
printf("Both values are less than 0\n");
}
return 0;
}

2. Logical OR Operator ( || )

The condition becomes true if any one of them is non-zero. Otherwise, it


returns false i.e., 0 as the value. Below is the truth table for the logical OR
operator.

X Y X || Y

1 1 1

1 0 1

0 1 1
0 0 0

Syntax
(operand_1 || operand_2)
#include <stdio.h>
int main()
{
int a = -1, b = 20;
if (a > 0 || b > 0) {
printf("Any one of the given value is "
"greater than 0\n");
}
else {
printf("Both values are less than 0\n");
}
return 0;
}

3. Logical NOT Operator ( ! )

If the condition is true then the logical NOT operator will make it false and
vice-versa. Below is the truth table for the logical NOT operator.

X !X

0 1

1 0

Syntax
!(operand_1 && operand_2)
#include <stdio.h>
int main()
{
int a = -1, b = 20;
if !(a > 0 || b > 0) {
printf("Any one of the given value is "
"greater than 0\n");
}
else {
printf("Both values are less than 0\n");
}
return 0;
}

2.4 Assignment operators


Assignment operators are used for assigning value to a variable. The left side
operand of the assignment operator is a variable and right side operand of the
assignment operator is a value. The value on the right side must be of the same
data-type of the variable on the left side otherwise the compiler will raise an
error.

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to


assign the value on the right to the variable on the left. Example:
a = 10;
b = 20;
ch = 'y';

2. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator
first adds the current value of the variable on left to the value on the right and
then assigns the result to the variable on the left. Example:
(a += b) can be written as (a = a + b)

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator
first subtracts the value on the right from the current value of the variable on
left and then assigns the result to the variable on the left. Example:
(a -= b) can be written as (a = a - b)

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator
first multiplies the current value of the variable on left to the value on the right
and then assigns the result to the variable on the left. Example:
(a *= b) can be written as (a = a * b)

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator
first divides the current value of the variable on left by the value on the right
and then assigns the result to the variable on the left. Example:
(a /= b) can be written as (a = a / b)

#include <stdio.h>
int main()
{
int a = 10;
printf("Value of a is %d\n", a);
a += 10;
printf("Value of a is %d\n", a);
a -= 10;
printf("Value of a is %d\n", a);
a *= 10;
printf("Value of a is %d\n", a);
a /= 10;
printf("Value of a is %d\n", a);
return 0;
}

2.7 Bitwise operators.

In C, the following 6 operators are bitwise operators (also known as bit


operators as they work at the bit-level).
&,|,<<,>>,~,^
1. The & (bitwise AND) in C takes two numbers as operands and does AND
on every bit of two numbers. The result of AND is 1 only if both bits are
1.

1. The | (bitwise OR) in C takes two numbers as operands and does OR on


every bit of two numbers. The result of OR is 1 if any of the two bits is 1.

1. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR
on every bit of two numbers. The result of XOR is 1 if the two bits are
different.

1. The << (left shift) in C takes two numbers, the left shifts the bits of the
first operand, and the second operand decides the number of places to
shift.

1. The >> (right shift) in C takes two numbers, right shifts the bits of the first
operand, and the second operand decides the number of places to shift.

1. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.

X Y X& Y X|Y X^Y

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

Unary Operators
2.5 Increment and Decrement operators
The increment ( ++ ) and decrement ( — ) operators in C are unary
operators for incrementing and decrementing the numeric values by
1 respectively.
Syntax of Increment Operator
Increment Operator can be used in two ways which are as follows:
// AS PREFIX
++m
// AS POSTFIX
m++
1.Pre-Increment
In pre-increment, the increment operator is used as the prefix. Also known as
prefix increment, the value is incremented first according to the precedence
and then the less priority operations are done.

Example
result = ++var1;

2.Post-Increment
In post-increment, the increment operator is used as the suffix of the operand.
The increment operation is performed after all the other operations are done. It
is also known as postfix increment.
Example
result = var1++;

Decrement Operator in C
The decrement operator is used to decrement the value of a variable in an
expression. In the Pre-Decrement, the value is first decremented and then used
inside the expression.
Syntax
Just like the increment operator, the decrement operator can also be used in
two ways:
// AS PREFIX
--m
// AS POSTFIX
m--

1.Pre-Decrement Operator
The pre-decrement operator decreases the value of the variable immediately
when encountered. It is also known as prefix decrement as the decrement
operator is used as the prefix of the operand.
Example
result = --m;
2.Post-Decrement Operator
The post-decrement happens when the decrement operator is used as the suffix
of the variable. In this case, the decrement operation is performed after all the
other operators are evaluated.
Example
result = m--;

#include<stdio.h>
int main()
{
int a = 5;
int b = 5;
int prefix = ++a;
printf("Prefix Increment: %d\n", prefix);
printf("Prefix Increment: %d\n", a);
int postfix = b++;
printf("Postfix Increment: %d \n", postfix);
printf("Postfix Increment: %d \n", b);
return 0;
}

#include<stdio.h>
int main()
{
int a = 5;
int b = 5;
int prefix = --a;
printf("Prefix Increment: %d\n", prefix);
printf("Prefix Increment: %d\n", a);
int postfix = b--;
printf("Postfix Increment: %d \n", postfix);
printf("Postfix Increment: %d \n", b);
return 0;
}

2.8. Special operators


Comma operator and sizeof operator.
The comma operator can be used to link the related expression together.
It has the lowest pripority
Value=(x=10,y=5,x+y);

Sizeof operator.
It is compile time operator and when used with an operand it returns the no of
bytes the operand occupies.
M=sizeof(sum);
N=sizeof(a);

#include <stdio.h>
int main()
{
int a;
float b;
char c;
printf("%d\n", sizeof(a));
printf("%d\n", sizeof(b));
printf("%d\n", sizeof(c));
return 0;
}

Type Casting and Conversion in C


In a programming language, the expression contains data values of the same
datatype or different data types. When the expression contains similar datatype
values then it is evaluated without any problem. But if the expression contains
two or more different datatype values then they must be converted to the single
datatype of destination datatype. Here, the destination is the location where the
final result of that expression is stored. For example, the multiplication of an
integer data value with the float data value and storing the result into a float
variable. In this case, the integer value must be converted to float value so that
the final result is a float datatype value.
In a c programming language, the data conversion is performed in two different
methods as follows...

1. Type Conversion
2. Type Casting

Type Conversion

The type conversion is the process of converting a data value from one data type
to another data type automatically by the compiler. Sometimes type conversion
is also called implicit type conversion. The implicit type conversion is
automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a
float variable the integer value automatically gets converted to float value by
adding decimal value 0. And when a float value is assigned to an integer
variable the float value automatically gets converted to an integer value by
removing the decimal value. To understand more about type conversion observe
the following...
Int i=10;

Float x = 20.9;

Char ch = ‘A’;

i = x ; ==> x value 20.9 is converted as 15 and assigned to variable i


x = i ; ==> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; ==> Here the ASCII value of A (65) is assigned to i

Typecasting - Typecasting is also called an explicit type conversion. Compiler


converts data from one data type to another data type implicitly. When compiler
converts implicitly, there may be a data loss. In such a case, we convert the data
from one data type to another data type using explicit type conversion. To
perform this we use the unary cast operator. To convert data from one type to
another type we specify the target data type in parenthesis as a prefix to the data
value that has to be converted. The general syntax of typecasting is as follows.

Ternary Operator:
2.6 Conditional operators
It is also known as the ternary operator in C as it operates on three operands.
variable = Expression1 ? Expression2 : Expression3;

It can be visualized into an if-else statement as:


if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}

#include <stdio.h>
int main()
{
int m = 5, n = 4;
(m > n) ? printf("m is greater than n that is %d > %d",
m, n)
: printf("n is greater than m that is %d > %d",
n, m);
return 0;
}

2.10 Arithmetic expression


An Arithmetic Expression is a combination of operands and Arithmetic
operators, such as addition, subtraction, and so on.
These combinations of operands and operators should be mathematically
meaningful, otherwise, they can not be considered as an Arithmetic expression
in C.

An arithmetic expression is an expression that consists of operands and


arithmetic operators. An arithmetic expression computes a value of type int,
float or double.

When an expression contains only integral operands, then it is known as pure


integer expression when it contains only real operands, it is known as pure real
expression, and when it contains both integral and real operands, it is known as
mixed mode expression.

There are 3 levels of precedence for 5 binary operators as given below:


Highest: Exponentiation (^)
Next highest: Multiplication (*) and division (/)
Lowest: Addition (+) and Subtraction (-)
For example –
Infix notation: (A-B)*[C/(D+E)+F]
Post-fix notation: AB- CDE +/F +*

2.11 Evaluation of expression


Evaluate an expression represented by a String. The expression can contain
parentheses, you can assume parentheses are well-matched. For simplicity, you
can assume only binary operations allowed are +, -, *, and /. Arithmetic
Expressions can be written in one of three forms:
 Infix Notation: Operators are written between the operands they operate on,
e.g. 3 + 4.
 Prefix Notation: Operators are written before the operands, e.g + 3 4
 Postfix Notation: Operators are written after operands.
Infix Expressions are harder for Computers to evaluate because of the additional
work needed to decide precedence. Infix notation is how expressions are written
and recognized by humans and, generally, input to programs.

2.12 Precedence of Arithmetic operators


The concept of operator precedence and associativity in C helps in
determining which operators will be given priority when there are multiple
operators in the expression.
It is very common to have multiple operators in C language and the compiler
first evaluates the operater with higher precedence. I
t helps to maintain the ambiguity of the expression and helps us in avoiding
unnecessary use of parenthesis

#include <stdio.h>
int main()
{
// Verifying the result of the same expression
printf("100 / 5 % 2 = %d", 100 / 5 % 2);
return 0;
}

2.13 Operator precedence and Associativity

Operator precedence determines the grouping of terms in an expression and


decides how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has a higher
precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has


a higher precedence than +, so it first gets multiplied with 3*2 and then adds
into 7.

Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.

Show Examples

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

2.14 Mathematical Functions

There is also a list of math functions available, that allows you to perform
mathematical tasks on numbers.

To use them, you must include the math.h header file in your program:

#include <math.h>
square Root

To find the square root of a number, use the sqrt() function:

Example
printf("%f", sqrt(16));
Round a Number

The ceil() function rounds a number upwards to its nearest integer, and
the floor() method rounds a number downwards to its nearest integer, and
returns the result:
Example
printf("%f", ceil(1.4));
printf("%f", floor(1.4));
Power

The pow() function returns the value of x to the power of y (xy):

Example
printf("%f", pow(4, 3));
#include <math.h>
#include <stdio.h>
int main()
{
printf("value1 = %f\n",sqrt(16));
printf("value2 = %f\n",pow(4,2));
printf("value3 = %f\n",ceil(12.8));
printf("value4 = %f\n",floor(12.4)); return (0); }

You might also like