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

unit 2 fpl

Uploaded by

uzair63210
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)
120 views

unit 2 fpl

Uploaded by

uzair63210
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/ 20

FPL Unit-II DIT,Pimpri

FPL Unit-II DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-18


Department of First Year Engineering Fundamentals of
Programming Languages
Unit- 2 Notes
--------------------------------------------------------------------------------------

Unit II: Operators and Expressions

2.1 Operators
Q. What is operator? Enlist and explain types of operators in C.
Ans.
 In C language, operators are symbols that represent operations to be performed on one
or more operands. They are the basic components of the C programming.
 C supports a rich set of built-in operators. We have already used several of them, such as
=, +, –, *, & and <.
 An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations. Operators are used in programs to manipulate data and variables.
They usually form a part of the mathematical or logical expressions.
 Operators are fundamental for manipulating data, making decisions, and controlling
program flow. They allow programmers to perform computations, compare values, and
manage memory efficiently.
 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.

Types of Operators in C

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators.

1
FPL Unit-II DIT,Pimpri

1. Arithmetic Operators
 Arithmetic operators in C are used to perform mathematical operations on variables and
constants.
 C provides all the basic arithmetic operators. The operators +, –, *, and / all work the
same way as they do in other languages. These can operate on any built-in data type
allowed in C. The unary minus operator, in effect, multiplies its single operand by –1.
Therefore, a number preceded by a minus sign changes its sign.

Here are the basic arithmetic operators:

Example:
Sr.No. Symbol Meaning Example Output
1 + Addition 5+3 8
2 - Subtraction 5-3 2
3 * Multiplication 5*3 15
4 / Division 6/3 2
5 % Modulus 5%3 2

Program Example:
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Addition: %d\n", a + b);
printf("Subtraction: %d\n", a - b);
printf("Multiplication: %d\n", a * b);
printf("Division: %d\n", a / b);
printf("Modulus: %d\n", a % b);
return 0;
}
Output:
Addition: 13
Subtraction: 7
Multiplication: 30

2
FPL Unit-II DIT,Pimpri

Division: 3
Modulus: 1

2. Relational Operators
 We often compare two quantities and depending on their relation, take certain decisions.
For example, we may compare the age of two persons, or the price of two items, and so
on. These comparisons can be done with the help of relational operators. We have
already used the symbol ‘<‘, meaning ‘less than’. An expression such as
a < b or 1 < 20

 containing a relational operator is termed as a relational expression. The value of a


relational expression is either one or zero. It is one true and zero if the relation is false.
For example

10 < 20 is true
but
20 < 10 is false

Here is the Example of relational operators:

Sr.No. Symbol Meaning Example Output


1 == Equal to 5 == 5 true
2 != Not equal to 5 != 3 true
3 > Greater than 5>3 true
4 < Less than 5<6 true
5 >= Greater than or equal to 5 >= 5 true
11 <= Less than or equal to 5 <= 6 true

Program Example:
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("a == b: %d\n", a == b); // 0 (false)
printf("a != b: %d\n", a != b); // 1 (true)
printf("a > b: %d\n", a > b); // 1 (true)

3
FPL Unit-II DIT,Pimpri

printf("a < b: %d\n", a < b); // 0 (false)


printf("a >= b: %d\n", a >= b); // 1 (true)
printf("a <= b: %d\n", a <= b); // 0 (false)
return 0;
}
Output:
a == b: 0
a != b: 1
a > b: 1
a < b: 0
a >= b: 1
a <= b: 0

3. Logical Operators
Logical operators are used to combine two or more conditions.

Sr.No. Symbol Meaning Example Output


1 && Logical AND (5 > 1) && (3 < 5) true
2 || Logical OR (5 > 1) || (6 < 5) true
3 ! Logical NOT !(5 == 3) true

 The logical operators && and || are used when we want to test more than one condition
and make decision. An example
a > b && x == 10.
 An expression of this kind, which combines two or more relational expressions,
is termed as a logical expression or a compound relational expression. Like the simple
relational expressions, a logical expression also yields a value of one or zero. The logical
expression given above is true only if a > b is true and x == 10 is true. If either (or
both) of them are false, the expression is false.

Program Example:
#include <stdio.h>
int main() {
int a = 1, b = 0;
printf("a && b: %d\n", a && b);
printf("a || b: %d\n", a || b);
printf("!a: %d\n", !a);
return 0;
}

4
FPL Unit-II DIT,Pimpri

Output:
a && b: 0
a || b: 1
!a: 0

4. Assignment Operators

 Assignment operators are used to assign the result of an expression to a variable. We


have seen the usual assignment operator, ‘=’. In addition, C has a set of ‘shorthand ’
assignment operators of the form
v op= exp;
 Where v is a variable, exp is an expression and op is a C binary arithmetic operator. The
operator = is known as the shorthand assignment operator.The assignment statement
v op= exp;
is equivalent to
v = v op (exp);
with v evaluated only once.
 Consider an example
x += y+1;
 This is same as the statement x = x + (y+1);
 The shorthand operator += means ‘add y+1 to x’ or ‘increment x by y+1’.
For y = 2, the above Statement becomes x += 3;
and when this statement is executed, 3 is added to x. If the old value of x is, say 5, then
the new value of x is 8. Some of the commonly used shorthand assignment operators
are illustrated in Table

Advantages of shorthand Assignment operators:


1. What appears on the left-hand side need not be repeated and therefore it becomes easier
to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.

Here is the Example Assignment operators:

Sr.No. Symbol Meaning Example Output


1 = Assignment int a = 5; a is 5
2 += Add and assign int a = 5; a += 3; a is 8
5
FPL Unit-II DIT,Pimpri

3 -= Subtract and assign int a = 5; a -= 3; a is 2


4 *= Multiply and assign int a = 5; a *= 3; a is 15
5 /= Divide and assign int a = 6; a /= 3; a is 2
6 %= Modulus and assign int a = 5; a %= 3; a is 2

Program Example:
#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
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("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("a >>= b: %d\n", a >> b);
printf("a <<= b: %d\n", a << b);

return 0;
}
Output:

a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5
a >>= b: 0
a <<= b: 160

5. Increment and Decrement Operators


 C allows two very useful operators not generally found in other languages. These are the
increment and decrement opearators.
++ and –
 The operator ++ adds 1 to the operand, while – – subtracts 1. Both are unary operators
and takes the following form
++m; or m++;
--m; or m--;
++m; is equivalent to m = m+1; (or m += 1;)
—m; is equivalent to m = m–1; (or m –= 1;)

6
FPL Unit-II DIT,Pimpri

We use the increment and decrement statements in for and while loops extensively.

 Rules for ++ and -- operators:

1. Increment and decrement operators are unary operators and they require variable
as their operands.
2. When postfix ++ (or --) is used with variable in an expression, the expression is
evaluated first using the original value of the variable and then the variable is
incremented (or decremented) by one.
3. When prefix ++ (or --) is used in an expression, the variable is incremented (or
decremented) first then the expression is evaluated using the new value of the variable.
4. The precedence and associatively of ++ and – – operators are the same as those of unary
+ and unary –.

These operators are used to increase or decrease the value of a variable by 1.

Sr.No. Symbol Meaning Example Output


1 ++ Increment int a = 5; a++; a is 6
2 -- Decrement int a = 5; a--; a is 4

Program Example:
#include <stdio.h>
int main() {
int a = 10;
printf("%d\n",a++); // a = a + 1 => a = 11
printf("%d\n",a--); // a = a - 1 => a = 10

int count = 5;
printf("%d\n", ++count); // prints 6 (prefix increment)
printf("%d\n", count--); // prints 6, then count becomes 5 (postfix decrement)

return 0;
}
Output:
10
11
6
6

7
FPL Unit-II DIT,Pimpri

6. Conditional Operators
The conditional operator in C is kind of similar to the 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. It is also known as the ternary operator in
C as it operates on three operands.

Sr.No. Symbol Meaning Example Output


23 ?: Conditional (Ternary) int max = (a > b) ? a : b; max is a or b

Syntax of Conditional/Ternary Operator in C


The conditional operator can be in the form
variable = Expression1 ? Expression2 : Expression3;
OR the syntax can also be in this form
variable = (condition) ? Expression2 : Expression3;

Program Example:
#include <stdio.h>
int main() {
int a = 10, b = 5;
int max = (a > b) ? a : b;
printf("Maximum value is %d\n", max);

return 0;
}
Output:
Maximum value is 10

7. Bitwise Operators
 C has a distinction of supporting special operators known as bitwise operators for
manipulation of data at bit level. These operators are used for testing the bits, or shifting
them right or left. Bitwise operators may not be applied to float or double.
Here are the bitwise operators:

Sr.No. Symbol Meaning Example Output


1 & Bitwise AND 5&3 1 (binary 0001)
2 | Bitwise OR 5|3 7 (binary 0111)
3 ^ Bitwise XOR 5^3 6 (binary 0110)
4 ~ Bitwise NOT ~5 -6 (two's complement)
5 << Left shift 5 << 1 10 (binary 1010)
6 >> Right shift 5 >> 1 2 (binary 0010)

8
FPL Unit-II DIT,Pimpri

Program Example:

#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("a & b: %d\n", a & b); // 1
printf("a | b: %d\n", a | b); // 7
printf("a ^ b: %d\n", a ^ b); // 6
printf("~a: %d\n", ~a); // -6
printf("a << 2: %d\n", a << 2); // 20
printf("a >> 2: %d\n", a >> 2); // 1
return 0;
}
Output:
a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 2: 20
a >> 2: 1

8. Special Operators
Special operators include sizeof, comma operator, pointer operators, etc.

 sizeof: Returns the size of a variable or datatype.


 Comma ‘,’: Separates expressions.
 Pointer *: Value at address.

8.1 Comma Opearator

 The comma operator can be used to link the related expressions together. A
comma-linked list of expressions are evaluated left to right and the value of right-most
expression is the value of the combined expression. For example, the statement
value = (x = 10, y = 5, x+y);
 first assigns the value 10 to x, then assigns 5 to y value, and finally assigns 15(i.e 10+5)
to value. Since comma operator has the lowest precedence of all operators, the
parentheses are necessary. Some applications of comma operator are:
In for loop:
for ( n = 1, m = 10, n <=m; n++, m++)
In while loop:
while (c = getchar( ), c != ‘10’)
9
FPL Unit-II DIT,Pimpri

exchanging values:
t = x, x = y, y = t;

8.2 sizeof operator :

 The sizeof is a compile time operator and, when used with an operand, it returns the
number of bytes the operand occupies. The operand may be a variable, a constant or a
data type qualifier.
Examples: m= sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
 The sizeof operator is normally used to determine the lengths of arrays and structures
when their sizes are not known to the programmer. It is also used to allocate memory
space dynamically to variables during execution of a program.

Program Example:
#include <stdio.h>
int main() {
int a = 10;
printf("Size of a: %lu\n", sizeof(a)); // 4 (bytes)
int b = (a, 20); // b = 20
printf("%d\n",b);
int *p = &a; // p stores the address of a
printf("Value at address p: %d\n", *p); // 10
return 0;
}
Output:
Size of a: 4
20
Value at address p: 10

2.2 Arithmetic Expression

Q. Explain Arithmetic Expression with suitable example.

An arithmetic expression is a combination of variables, constants, and operators arranged as per


the syntax of the language. We have used a number of simple expressions in the examples
discussed so far. C can handle any complex mathematical expressions. Remember that C does
not have an operator for exponentiation.

Here’s a breakdown:
10
FPL Unit-II DIT,Pimpri

 Variables: Represent values that can change during the execution of a program.
 Constants: Fixed values that do not change during program execution.
 Operators: Symbols like +, -, *, /, % that perform arithmetic operations (addition, subtraction,
multiplication, division, modulus) on variables and constants.

Program Example:

#include <stdio.h>

int main() {

int a = 10, b = 3, c;

c = a + b * 2; // c = 10 + 3*2 = 10 + 6 = 16

printf("%d\n",c);

return 0;

Output:

16

2.3 Evaluation of Expressions


Q. Explain in brief about evaluation expression. Or what are the types of expression in C.

Ans.

Evaluation of Expressions:

 Expressions are evaluated using an assignment statement of the form:

variable=expression;

11
FPL Unit-II DIT,Pimpri

 Variable is any valid C variable name. when the statement is encountered, the expression
is evaluated first and then the replaces the previous value of a variable on the left hand
side. All variables used in expression must be assigned values before evaluation is
attempted.

Examples of evaluation statements are:

x = a * b - c;

y = b / c * a;

z = a – b / c + d;

 The blank space around an operator is optional and adds only to improve readability.
When these statements are used in program, the variable a, b, c and d must be defined
before they used in the expressions.

Example:

#include <stdio.h>

int main() {

float a,b,c,x,y,z;

a=9;

b=12;

c=3;

x=a-b/3+c*2-1;

y=a-b/(3+c)*(2-1);

z=a-(b/(3+c)*2)-1;

printf("x= %f\n",x);

printf("y= %f\n",y);

printf("z= %f\n",z);

Output:
x= 10.000000
12
FPL Unit-II DIT,Pimpri

y= 7.000000
z= 4.000000
Types of expression
 Infix Expressions
Infix expressions are the most common form of expressions in C and other programming languages. In an
infix expression, the operator is placed between the operands.
Example:

int result = 3 + 4 * 2; // Infix expression


In this example, + and * are infix operators.

 Prefix Expressions
Prefix expressions, also known as Polish notation, have the operator placed before the operands. While C
doesn't natively support prefix expressions in the way it does infix, you can evaluate prefix expressions
using data structures like stacks.
Example of Prefix Expression: + 3 4
To evaluate prefix expressions in C, you can write a program using a stack to convert and evaluate them.

 Postfix Expressions
Postfix expressions, also known as Reverse Polish notation (RPN), have the operator placed after the
operands. Similar to prefix expressions, C doesn't natively support postfix expressions but you can
evaluate them using stacks.
Example of Postfix Expression: 3 4 +

2.4 Precedence of Arithmetic Operators

Q. what is precedence of Arithmetic Operators? Explain Rules for Evaluation of Expression.

 Operators in C have a predefined precedence (priority) which determines the order in


which operations are performed. Multiplication (*) and division (/) have higher
precedence than addition (+) and subtraction (-).
 An arithmetic expression without parentheses will be evaluated from left to right
using the rules of precedence of operators. There are two distinct priority levels of
arithmetic operators in C:
High priority * / %
Low priority +
 The basic evaluation procedure includes ‘two’ left-to-right passes through the
expression. During the first pass, the high priority operators (if any) are applied as they
are encountered. During the second pass, the low priority operators (if any) are applied
as they are encountered. Consider the following evaluation statement that has been used
x = a-b/3 + c*2-1

When a = 9, b = 12, and c = 3, the statement becomes

x = 9-12/3 + 3*2-1

13
FPL Unit-II DIT,Pimpri

and is evaluated as follows


fig. Hierarchy of operations

2.4.1 Rules for Evaluation of Expression

1. First, parenthesized sub expression from left to right are evaluated.


2. If parentheses are nested, the evaluation begins with the innermost sub-expression.
3. The precedence rule is applied in determining the order of application of operators in
evaluating sub-expressions.
4. The associativity rule is applied when two or more operators of the same precedence
level appear in a sub-expression.
5. Arithmetic expressions are evaluated from left to right using the rules of precedence.
6. When parentheses are used, the expressions within parentheses assume highest
priority

Program Example:

#include <stdio.h>

int main() {

int result = 10 + 5 * 2; // Result is 20, not 30 because * has higher precedence


than +

printf("%d\n",result);

return 0;

}
14
FPL Unit-II DIT,Pimpri

Output:

20

2.5 Operator Precedence and Associativity


2.5.1 Operator Precedence

 Operator precedence determines which operation is performed first in an expression with


more than one operator with different precedence.

Let’s try to evaluate the following expression,

10 + 20 * 30

The expression contains two operators, + (plus), and * (multiply). According to the given table,
the * has higher precedence than + so, the first evaluation will be

10 + (20 * 30)

After evaluating the higher precedence operator, the expression is

10 + 600

Now, the + operator will be evaluated.

610

2.5.2 Operator Associativity

 Operator associativity is used when two operators of the same precedence appear in an
expression. Associativity can be either from Left to Right or Right to Left.

Example
Let’s evaluate the following expression,

100 / 5 % 2

 Both / (division) and % (Modulus) operators have the same precedence, so the order of
evaluation will be decided by associativity.
 According to the given table, the associativity of the multiplicative operators is from Left to
Right. So,

(100 / 5) % 2

After evaluation, the expression will be

20 % 2
15
FPL Unit-II DIT,Pimpri

Now, the % operator will be evaluated.

Description Associativity
Operator
Precedence

() Parentheses (function call)

[] Array Subscript (Square Brackets)

1 . Dot Operator Left-to-Right

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

!,~ Logical NOT, Bitwise complement


2 Right-to-Left
* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

< , <= Relational less than, less than or equal to


6 Left-to-Right
> , >= Relational greater than, greater than or

16
FPL Unit-II DIT,Pimpri

Description Associativity
Operator
Precedence

equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division assignment

14 Right-to-Left
%= , &= Modulus, bitwise AND assignment

Bitwise exclusive, inclusive OR


^= , |=
assignment

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right

 Rules of Precedence and Associativity


1. Precedence rules decides the order in which different operators are applied.
2. Associativity rule decides the order in which multiple occurrences of the same level
operator are applied.

17
FPL Unit-II DIT,Pimpri

 Easy Trick to Remember the Operators Associativity and Precedence:

PUMA’S REBL TAC

where, P = Postfix, U = Unary, M = Multiplicative, A = Additive, S = Shift, R =


Relational, E = Equality, B = Bitwise, L = Logical, T = Ternary, A = Assignment and C =
Comma

2.6 Mathematical Functions

 Mathematical functions such as cos, sqrt, log, etc. are frequently used in analysis of real-
life problems.
 Most of the C compilers support these basic math functions. However, there are systems
that have functions are available. Table 3.9 lists some standard math functions.
 Mathematical functions in C are provided by the <math.h> library, which offers a variety
of functions to perform mathematical operations.
 The math.h library provides various mathematical functions like sqrt, pow, sin, etc.

Function Description Example Result


sqrt(x) Square root of x sqrt(25.0) 5.0
pow(x, y) x raised to the power y pow(2.0, 3.0) 8.0
sin(x) Sine of x (x in radians) sin(0.0) 0.0
tan(x) Tangent of x (x in radians) tan(0.0) 0.0
log(x) Natural logarithm (base e) of x log(2.71828) 1.0
log10(x) Base-10 logarithm of x log10(100.0) 2.0
exp(x) Exponential of x (e^x) exp(1.0) 2.71828
ceil(x) Rounds x up to the nearest integer ceil(2.3) 3.0
floor(x) Rounds x down to the nearest integer floor(2.7) 2.0
Table basic math function

18
FPL Unit-II DIT,Pimpri

Question bank
1. What are the different arithmetic operators in C? Provide examples for each.
2. How does integer division differ from floating-point division in C.
3. List all relational operators in C and give an example of each.
4. Write a C program to compare two integers and display whether they are equal or not.
5. How do relational operators interact with if-else statements in C?
6. What are the logical operators available in C? Provide examples.
7. Explain the difference between the logical AND (&&) and logical OR (||) operators with
examples. What is the result of the expression (5 > 3) && (3 < 2)? Explain.
8. List different assignment operators in C. Explain the difference between = and == in C
9. How do compound assignment operators (e.g., +=, -=) work in C? Provide examples.
10. Write a C program demonstrating the use of assignment operators.
11. What are the increment and decrement operators in C? Provide examples.
12. What will be the output of the following code snippet?

#include <stdio.h>
int main() {
int x = 5;
printf("%d\n", x++);
printf("%d\n", ++x);
return 0;
}

13. What is the conditional (ternary) operator in C? Provide the syntax and an example.
14. Write a C program using the conditional operator to find the largest of two numbers.
15. List all the bitwise operators in C and give an example of each.
16. How does the bitwise shift operator (<<, >>) work? Provide examples.
17. What are the special operators in C? Explain the purpose of the sizeof operator with an
example.
18. What is the purpose of the comma operator? Provide an example.
19. Write a C program demonstrating the use of the sizeof operator on different data types.
20. What are arithmetic expressions in C? Provide examples.
21. Explain the order of evaluation of the expression a + b * c - d / e.
22. What is operator precedence? Why is it important in C?
23. List the precedence of arithmetic operators in C from highest to lowest.
24. How does precedence affect the evaluation of the expression a + b * c?
25. Explain the difference between operator precedence and associativity. What is the
associativity of the arithmetic operators in C?
26. What are some common mathematical functions available in C? Provide examples.
27. How do you include and use the math library in a C program? Explain the use of the sqrt
and pow functions with examples.

19
FPL Unit-II DIT,Pimpri

Practice Programs

1. Write a program to perform addition, subtraction, multiplication, division, and modulus


operations on two integers entered by the user.
2. Write a program to compare two integers entered by the user and print the results of the
comparisons using relational operators.
3. Write a program to demonstrate the use of logical operators by checking if an integer entered by
the user is positive, even, and greater than 100.
4. Write a program to demonstrate the use of various assignment operators by performing
operations on an integer entered by the user.
5. Write a program to demonstrate the use of increment and decrement operators on an integer
entered by the user.
6. Write a program to find the largest of two numbers using the conditional operator.
7. Write a program to demonstrate the use of bitwise operators by performing operations on two
integers entered by the user.
8. Write a program to demonstrate the use of the sizeof operator on different data types.
9. Write a program to evaluate a simple arithmetic expression involving addition, subtraction,
multiplication, and division.
10. Write a program to calculate the square root and power of a number using the math library
functions sqrt and pow.
11. Find solution to a Quadratic Equation ax2+bx+c=0

20

You might also like