0% found this document useful (0 votes)
24 views18 pages

Unit 4

Uploaded by

Samir Shrestha
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)
24 views18 pages

Unit 4

Uploaded by

Samir Shrestha
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/ 18

Unit-4 Operators and Expression

Operators
 An operator is a symbol that operates on single or multiple data items.
 Used in program to perform certain mathematical or logical manipulations.
 The data items that operator act upon are called operands.
 E.g. In a simple expression 2+3, the symbol “+” is called an operator which operates on
two data items 2 and 3.

Expression
 An expression is a combination of variables, constants and operators written according to
syntax of the language. E.g. 7+8, x+y*z, a>b

Operator classification
a. According to Number of Operands
 Unary operators
The operators which require only one operand to operate are called unary operators.
E.g. ++ (increment), -- (decrement) + (unary plus) and - (unary minus) are unary
operators.
 Binary Operators
The operators which require two operands to operate are called binary operators. E.g.:
+ (plus), - (minus), *(multiply), / (division), <(less than), > (greater than), etc. are
binary operators.
 Ternary Operators
The operators which require three operands to operate are called ternary operators.

b. According to Utility and Action


 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional Operators
 Bitwise Operators
 Special Operators

1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations. There are five arithmetic
operators in C which are listed in table:
Division Rule:
 int/int = int
 float/float = float
 int/float = float
 float/int = float

Note: For modulo operator, the sign of the result is always the sign of the first operand. E.g.
10%3=1, -10%3=-1, -10%-3=-1, 10%-3=1 2

/* Program to Perform Arithmetic Operations in C */


#include <stdio.h>
int main()
{
int a = 12, b = 3;
int add, sub, mul, div, mod;
add = a + b;
sub = a - b;
mul = a * b;
div = a / b;
mod = a % b;
printf("Addition of two numbers a, b is : %d\n", add);
printf("Subtraction of two numbers a, b is : %d\n", sub);
printf("Multiplication of two numbers a, b is : %d\n", mul);
printf("Division of two numbers a, b is : %d\n", div);
printf("Modulus of two numbers a, b is : %d\n", mod);
}
/* Program to convert number of days into month and days */

#include <stdio.h>
int main()
{
int days, months, remainingDays;
printf("Enter the number of days: \n");
scanf("%d", &days);

months = days / 30; // Assuming an average of 30 days per month


remainingDays = days % 30; // Calculate remaining days after considering months

printf("Equivalent: %d month(s) and %d day(s)\n", months, remainingDays);

return 0;
}

2. Relational Operators
Relational operators are used to compare two operands and taking decisions based on their relation.
 Result of relational expression is either True (1) or False (0).
 Relational operators are used in decision making and loops.
 Relational operators are:
/* Program to compare two numbers whether they are equal or not in C */
#include<stdio.h>
int main()
{
int m=40, n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}

3. Logical Operators
 Logical operators are used to compare logical and relational expression.
 The operands of logical operators must be either Boolean value (1 or 0) or expression that
produces Boolean value.
 The output of these operators is always 0 (flase) or 1 (true).
 The logical operators are: Truth table for logical operators:
/* C program to demonstrate working of logical operators */

#include <stdio.h>

int main() {
int a = 5, b = 10, c = 15;

// Using logical AND (&&)


if (a < b && b < c) {
printf("Both conditions are true (a < b < c)\n");
} else {
printf("At least one condition is false\n");
}

// Using logical OR (||)


if (a == b || b == c) {
printf("At least one condition is true (a equals b or b equals c)\n");
} else {
printf("Both conditions are false\n");
}

// Using logical NOT (!)


if (!(a == b)) {
printf("a is not equal to b\n");
} else {
printf("a is equal to b\n");
}

return 0;
}

4. Assignment Operator
 Assignment operators are used to assign the values of an expression to a variable.
 The mostly used assignment operator is ‘=’.
 C also supports shorthand assignment operators which simplify operation with assignment.
/* program to demonstrate working of Assignment operators */
#include<stdio.h>
int main()
{
int a = 10;
printf("Value of a is %d\n", a); //10
a += 10;
printf("Value of a is %d\n", a); //20
a -= 10;
printf("Value of a is %d\n", a); //10
a *= 10;
printf("Value of a is %d\n", a); //100
a /= 10;
printf("Value of a is %d\n", a); //10
return 0;
}

5. Increment and Decrement Operators


 Increment operator is used to increase the value of an operand by 1.
 Decrement operator is used to decrease the value of an operand by 1.
Pre-increment operator (++a): the value is incremented first and then the expression is evaluated.
E.g. a= 10; b=++a; after this statement, a= 11, b = 11.
Post-increment operator (a++): the expression is evaluated first and then the value is
incremented.
E.g. a= 10; b=a++; after this statement, a= 11, b = 10.
Pre-decrement operator (- -a): the value is decremented first and then the expression is
evaluated.
E.g. a= 10; b=--a; after this statement, a= 9, b = 9.
Post-decrement operator (a- -): the expression is evaluated first and then the value is
decremented.
E.g. a= 10; b=a--; after this statement, a= 9, b = 10.
/* program to demonstrate working of increment and decrement operators */
#include<stdio.h>
int main()
{
int a = 5;
int b = 6;
printf("a=%d, b=%d",a,b); //a=5, b=6
b=++a;
printf("a=%d, b=%d",a,b); //a=6,b=6
b=a++;
printf("a=%d, b=%d",a,b); //a=7,b=6
b=a--;
printf("a=%d, b=%d",a,b); //a=6,b=7
b=--a;
printf("a=%d, b=%d",a,b); //a=5, b=5
return 0;
}

6. Conditional Operator (Ternary Operator)


 It takes three arguments.
 Conditional operators return one value if condition is true and returns another value if condition
is false.
 Syntax: (condition) ? value_if_true : value_if_false
/* program to read two numbers from user and determine the larger number using conditional
(ternary) operator */
#include <stdio.h>
int main()
{
int n1, n2, larger;
printf("Enter two numbers:");
scanf("%d%d",&n1,&n2);
larger = (n1>n2)?n1:n2;
printf("The larger number is %d", larger);
return 0;
}

7. Bitwise Operator
 Bitwise operators are used for manipulating data at bit level.
 These operators are used for testing the bits or shifting them to the left or to the right.
 Can be applied only to integer-type operands and not to float or double.
 Three types of bitwise operators:
i. Bitwise logical operators
ii. Bitwise shift operators
iii. One’s compliment operators

Bitwise logical operators:


 Performs logical tests between two integer-type operands.
 These operators work on their operands bit-by-bit starting from the least significant (i.e.
rightmost) bit.
 Three logical bitwise operators:
 Bitwise AND (&): The result of ANDing operation is 1 if both the bits have a value 1;
otherwise it is 0.
 Bitwise OR (|): The result of ORing operation is 1 if either of the bits have value of 1;
otherwise it is 0.
 Bitwise XOR (^): The result of exclusive ORing operations is 1 only if one of the bits
have a value of 1; otherwise it is 0.
Truth table for bitwise operators (AND, OR, XOR)

E.g.
If a = 65, b=15
Equivalent binary values of 65 = 0100 0001; 15 = 0000 1111

Bitwise shift operators:


 Are used to move bit patterns either to left or to the right.
 There are two bitwise shift operators:
 Left shift(<<): Causes the operand to be shifted to the right by n positions.
operand<<
The leftmost n bits in the original bit pattern will beloost and the rightmost n bits emptyposition
will be filled with 0’s.
 Right shift(>>): Causes the operand to be shifted to the right by n positions.
operand>>n
The empty leftmost n bits position will be filled with 0’s, if the operand is an unsigned integer.

Bitwise one’s complement operator:


 It is a unary operator which inverts all the bits represented by its operand. This means that all 0s
becomes 1s and 1s becomes 0s.
E.g.
If a =15; Equivalent binary value of a is 0000 1111

/* program to demonstrate working of bitwise operator*/


#include<stdio.h>
void main()
{
int a=65,b=15,AND, OR, XOR;
AND = a&b;
OR = a|b;
XOR = a^b;
printf("AND of a and b=%d\n",AND);
printf("OR of a and b=%d\n",OR);
printf("XOR of a and b=%d\n",XOR);
}

#include<stdio.h>
void main()
{
unsigned int a=15, left, right;
left = a<<3;
right =a>>2;
printf("%d\n", left);
printf("%d\n",right);
}

8. Special Operators
 Comma operator (,):
 The comma operator can be used link related expressions together.
 A comma-linked list of expression are evaluated from left-to-right and the value of the rightmost
expression is the value of the combined expressions.
E.g. X=(a=5, b=10, a+b);
 The first assign the value 5 to a
 Assign the value 10 to b
 Assign sum(a+b) to X

 Sizeof operator
 It is used with an operand to return the number of bytes it occupies.
 The operand may be constant, variable or a data type qualifier.

The syntax of sizeof operator is


sizeof(object);
E.g.
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}

Operator precedence and associativity


 The precedence is used to determine how an expression involving more than one operator is
evaluated.
 There are distinct level of precedence.
 The operator at the higher level of precedence are evaluated first.
 Operators of same precedence are evaluated either from “left to right” or “right to left” depending
on the level also known as associativity.
Type conversion in expressions
 When variables and constants of different types are combined in an expression then they are
converted to same data type.
 The process of converting one predefined type into another is called type conversion.
 Type conversion in C can be classified into the following two types:

1. Implicit Type Conversion:


 When the type conversion is performed automatically by the compiler without
programmer‘s intervention, such type of conversion is known as implicit type
conversion or type promotion.
 When the expression contains different types of data items, the operand with a
lower rank will be converted to the type of higher rank operand.
E.g.
#include<stdio.h>
int main()
{
int x = 13; // integer x
char c = 'a'; // character c
float sum;
x = x + c; // c implicitly converted to int. ASCII ('a'=97)
sum = x + 1.0; // x is implicitly converted to float
printf("x = %d, sum = %f", x, sum);
return 0;
}
2. Explicit Type Conversion:
 The type conversion performed by the programmer by posing the data type of the
expression of specific type is known as explicit type conversion.
 The explicit type conversion is also known as type casting.
 Type casting in C is done in the following form:
(data_type)expression;
Where, data_type is any valid C data type, and expression may be constant, variable or expression.
E.g.
#include<stdio.h>
int main()
{
float a = 1.2;
int b;
b = (int)a + 1; // a is explicitly converted to int type
printf("Value of a is %f\n", a);
printf("Value of b is %d\n",b);
return 0;
}
Evaluation of Expression

In C language, an expression is a combination of values, variables, operators, and function calls


that can be evaluated to produce a single value. Expressions can include arithmetic operations,
logical operations, assignments, function calls, and more.

Here's a brief breakdown of expressions in C:

Arithmetic Expressions: Involving arithmetic operators like +, -, *, /, and % (addition,


subtraction, multiplication, division, and modulus respectively) used with numeric values or
variables.

Example: int result = 10 + 5 * 3; (evaluates to 25)

Relational Expressions: Comparing values using relational operators like <, >, <=, >=, ==, !=
(less than, greater than, less than or equal to, greater than or equal to, equal to, not equal to).

Example: int comparison = (5 > 3); (evaluates to 1 for true, 0 for false)

Logical Expressions: Using logical operators like &&, ||, ! (logical AND, logical OR, logical
NOT) to combine multiple conditions.

Example: int condition = (a > 5 && b < 10); (evaluates to 1 for true, 0 for false)

Assignment Expressions: Assigning values using the assignment operator =.

Example: int x = 10;

Ternary Expressions: Using the conditional operator ? : to make a decision based on a condition.

Example: int result = (a > b) ? a : b; (assigns the larger value of a or b to result)

Expressions can be as simple as a single value or can involve complex combinations of operators
and operands. They are evaluated following the rules of precedence and associativity defined by
the C language, where certain operators have higher precedence than others, determining the order
of evaluation.
Pre-increment and post-increment

Here’s a comparison table to illustrate the differences between pre-increment (++var) and post-
increment (var++) operators:

The pre-decrement (--var) and post-decrement (var--) operators operate similarly to their
increment counterparts but with a decrement operation.

Here's a comparison table for pre-decrement and post-decrement operators:

Just like with increments, the key difference lies in whether the decrement occurs before or after
the current value of the variable is used within an expression.

You might also like