Operators

1 / 85

# Operators - PowerPoint PPT Presentation

Operators. Definition “An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables” Ex: a+b. Operators. Arithmetic operators Relational operators Logical operators

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### Operators

Definition

“An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables”

Ex: a+b

Operators
• Arithmetic operators
• Relational operators
• Logical operators
• Assignment operators
• Increment and decrement operators
• Conditional operators
• Bitwise operators
• Special operators

Here a and b are variables and are known as operands.

• Integer Arithmetic:

when both the operands in a single arithmetic expression such as a+b are integers.

The expression is called an integer expression, and the operation is called an integer arithmetic.

Examples: if a=14, b=4 then

a-b=10

a+b=18

a*b=56

a/b=3 (decimal part is truncated)

a%b=2 (remainder of division)

In Integer Division , 6/7=0;

-6/-7=0;

-6/7 is 0 or -1.

In modulo division, the sign of the result is always the sign of the first operand.

-14%3=-2;

-14%-3 =-2;

14%-3=2;

• Real Arithmetic:
• An arithmetic operation involving only real operands is called real arithmetic.

If x, y and z are floats ,then we will have

x=6.0/7.0=0.857143

y=1.0/3.0=0.333333

z=-2.0/3.0=-0.666667

The operator % can not be used with real operands.

Mixed Mode Arithmetic:

When one of the operands is real and the other is integer, the expression is called a mixed-mode arithmetic expression.

If either operand is of the real type, then only the real operation is performed and the result is always a real number.

15/10.0=1.5

where as

15/10=1

Example

#include <iostream>

using namespace std;

main()

{

int a = 21;

int b = 10;

int c ;

c = a + b;

cout << "Line 1 - Value of c is :" << c << endl ;

c = a - b;

cout << "Line 2 - Value of c is :" << c << endl ;

c = a * b;

cout << "Line 3 - Value of c is :" << c << endl ;

c = a / b;

cout << "Line 4 - Value of c is :" << c << endl ;

c = a % b;

cout << "Line 5 - Value of c is :" << c << endl ;

return 0;

}

OUTPUT
• Line 1 - Value of c is :31
• Line 2 - Value of c is :11
• Line 3 - Value of c is :210
• Line 4 - Value of c is :2
• Line 5 - Value of c is :1

An expression containing a relational operator is termed as a relational expression.

• Ex: a<b or 1<20
• The value of a relational expression is either one or zero.
• 1 –true
• 0-false
• Relational expressions are used in decision statements such as if and while .
Examples
• 4.5 <= 10 TRUE
• 4.5 < -10 FALSE
• -35 >=0 FALSE
• 10 <7+5 TRUE
• a+b =c+d TRUE iff sum of values of and b is equal to the sum of values of c and d.
Relational operator Complements
• > is complement of <=
• < is complement of >=
• == is complement of !=

Logical operators && and || are used when we want to test more than one condition and make decisions.

Ex: a>b && x==10

• An expression that combines two or more relational expressions is called as Logical expression or a compound relational expression
• Ex: if (a==b && b==c)
Relative Precedence

Highest !

> >= < <=

== !=

&&

Lowest ||

Assignment operators

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

Assignment Operator ‘=‘.

Syntax:

v op = exp;

Where v = variable,

op = shorthand assignment operator

exp = expression

Ex: x=x+3

x+=3

• What appears on the left-hand side need not be repeated and therefore it becomes easier to write.
• The statement is more concise and easier to read.
• The statement is more efficient.
Program for bitwise operators

#include <iostream.h>

using namespace std;

main()

{

unsigned int a = 60; // 60 = 0011 1100

unsigned int b = 13; // 13 = 0000 1101

int c = 0;

c = a & b; // 12 = 0000 1100

cout << "Line 1 - Value of c is : " << c << endl ;

c = a | b; // 61 = 0011 1101

cout << "Line 2 - Value of c is: " << c << endl ;

c = a ^ b; // 49 = 0011 0001

cout << "Line 3 - Value of c is: " << c << endl ;

c = ~a; // -61 = 1100 0011

cout << "Line 4 - Value of c is: " << c << endl ;

c = a << 2; // 240 = 1111 0000

cout << "Line 5 - Value of c is: " << c << endl ;

c = a >> 2; // 15 = 0000 1111

cout << "Line 6 - Value of c is: " << c << endl ; return 0;

}

output
• Line 1 - Value of c is : 12
• Line 2 - Value of c is: 61
• Line 3 - Value of c is: 49
• Line 4 - Value of c is: -61
• Line 5 - Value of c is: 240
• Line 6 - Value of c is: 15
Increment & Decrement Operators

C supports 2 useful operators namely

• Increment ++
• Decrement --operators

The ++ operator adds a value 1 to the operand

The -- operator subtracts 1 from the operand

++a or a++ (++a is equivalent to a=a+1 or a+=1;)

--a or a-- (--a is equivalent to a=a-1 or a-=1);

Rules for ++ & -- operators
• These require variables as their operands
• When postfix either ++ or – is used with the variable in a given expression, the expression is evaluated first and then it is incremented or decremented by one
• When prefix either ++ or – is used with the variable in a given expression, it is incremented or decremented by one first and then the expression is evaluated with the new value
Examples for ++ & -- operators

Let the value of a =5 and b=++a then

a = b =6

Let the value of a = 5 and b=a++ then

a =6 but b=5

i.e.:

1. a prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left

2. a postfix operator first assigns the value to the variable on left and then increments the operand.

program for increment operator :

#include <iostream>

using namespace std;

main()

{

int a = 21;

int c ;

// Value of a will not be increased before assignment.

c = a++;

cout << "Line 1 - Value of a++ is :" << c << endl ;

// After expression value of a is increased

cout << "Line 2 - Value of a is :" << a << endl ;

// Value of a will be increased before assignment.

c = ++a;

cout << "Line 3 - Value of ++a is :" << c << endl ;

return 0;

}

OUTPUT

Line 1 - Value of a++ is :21

Line 2 - Value of a is :22

Line 3 - Value of ++a is :23

Conditional operators

A ternary operator pair “? : “ is available in c to construct conditional expressions of the form

Syntax:

exp1 ? exp2 : exp3

where exp1,exp2 and exp3 are expressions

Working of the ? Operator:

Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is evaluated and this becomes the value of the expression,

If exp1 is false(0/zero) exp3 is evaluated and its value becomes the value of the expression

Ex: m=2;

n=3

r=(m>n) ? m : n;

#include <iostream>

using namespace std;

int main ()

{

// Local variable declaration:

int x, y = 10;

x = (y < 10) ? 30 : 40;

cout << "value of x: " << x << endl;

return 0;

}

output
• value of x: 40
Bitwise operators

These operators allow manipulation of data at the bit level.

These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits.

Special operators
• Comma operator ( ,)
• sizeof operator – sizeof( )
• Pointer operators – ( & and *)
• Member selection operators – ( . and ->)
• sizeof() operator is used to find the memory space allocated for each C data types.
Operators in C++
• :: scope resolution operator
• ::* pointer-to member declarator
• ->* pointer-to member operator
• .* pointer-to member operator
• delete memory release operator
• new memory allocation operator
• endl linefeed operator
• setw field width operator
new
• An object can be created using ‘new ‘operator.
• A data object created inside a block with new,will remain in existence until it is explicitly destroyed by using delete.

Syntax:

pointer _variable=new data-type;

Ex: p=new int;

q=new float;

Here, pointer_variable is a pointer of type data-type.

• The new operator allocates sufficient memory to hold data object of type data-type and returns the address of the object.

int *p = new int;

float *q=new float

// initializing the memory using new

• pointer_variable = new data_type (value);

int *p = new int(25);

//create memory space for array

Pointer_variable = new data_type [size];

int *p=new int[10];

delete
• when a data object is no longer needed, it is destroyed to release the memory space for reuse.
• delete pointer_varaible;
• Ex: delete p;
• delete [size] pointer_varaible;
• Ex: delete []p;
Use of new and delete operators

#include<iostream.h>

void main()

{

int *arr;

int size;

cout<< “enter size of the integer array”;

cin>>size;

cout<<“creating an array of size”<<size;

arr = new int[size];

cout<<“memory allocated successfully”;

delete arr;

getch();

}

output
• enter size of the integer array 6
• creating an array of size 6
• memory allocated successfully

#include <iostream>

using namespace std;

int main ()

{

double *pvalue = NULL; // Pointer initialized with null

pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address

cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;

}

output
• Value of pvalue: 29494.99

Note:

• If sufficient memory is not available for allocation, then new returns a null pointer.

p=new int;

if(!p)

{

cout<<“allocation failed”;

}

• It automatically computes the size of the data object. Need not use sizeof operator.
• It automatically returns the correct pointer type , so that there is no need to use a type cast.
• It is possible to initialize the object while creating the memory space.
• Like any other operator, new and delete can be overloaded.
Manipulators
• Manipulators are used to format the data display.
• endl
• setw
Using endl and setw

#include<iostream.h>

#include<iomanip.h>

using namsapce std;

int main()

{

int basic=950,allowance=95,tot=1045;

cout<<setw(10)<<“basic”<<setw(10)<<basic<<endl

<< setw(10)<<“allowance”<<setw(10)<<allowance<<endl

<<setw(10)<<“total”<<setw(10)<<total<<endl;

return 0;

}

output

basic= 950

allowance= 95

tot= 1045

The precision of the floating point numbers can also be controlled by using the following manipulators

i) fixed

ii) setprecision()

cout<<fixed<<setprecision(2)<<average;

Type conversion
• If data types are mixed in an expression, c++ performs the conversions automatically.
• This process is known as implicit or automatic conversion.
• When ever a char or short int appears in the expression, it is converted into int.
• This is called as integral widening conversion.
Type conversion

#include<iostream.h>

int main()

{

int count=7;

float avgweight=155.5F;

double totweight=count*avgweight;

cout<<“total weight=“<<totweight<<endl;

return 0;

}

Type Cast operator
• C++ permits explicit type conversion of variables or expressions using the type cast operator.
• Syntax

type-name (expression)

Ex: avg=sum/float(i);

Explicit Typecasting

#include<iostream.h>

#include<conio.h>

int main()

{

int a=25;

float b=35.78;

int c =65;

cout<<“a=“<<a;

cout<<“\nb=“<<b;

cout<<“\nfloat(a)=“<<float(a);

cout<<“\nint(b)=“<<int(b);

cout<<“\nchar(c)=“<<char(c);

getch();

}

output

a=25

b=35.78

float(a)=25

int(b)=35

char(c)=A

C++ cast operators
• const_cast
• static_cast
• dynamic_cast
• reintrepret_cast
Expressions
• An expression is a sequence of operands and operators that reduces to a single value.
• Expressions can be simple or complex.
• A simple expression contains only one operator.
• Ex:2+5 is a simple expression whose value is 7.
• A complex expression contains more than one operator. Ex: 2+5*7
• An arithmetic expression is a combination of variables, constants and operators arranged as per the syntax of the language.

Expressions may be of 7 types

• Constant Expressions
• Integral Expressions
• Float Expressions
• Pointer Expressions
• Relational Expressions
• Logical Expressions
• Bitwise Expressions

Constant Expressions :

Constant Expressions consists of only constant values.

Ex:

15

20+5/2.0

‘x’

Integral Expressions

The expressions which produce integer results after implementing all the automatic and explicit and type conversions are called Integral Expressions.

Ex: m and n are integer values.

m

m *n -5

m * ‘x’

5 + int(2.0)

Float Expressions

Float Expressions are those which , after all conversions, produce floating-point results.

Ex:

x+y

x*y /10

5 + float (10)

10.75

Pointer Expressions

• pointer Expressions produce address values.
• Example:

&m

ptr

ptr+1

“xyz”

m is a variable and ptr is a pointer

Relational Expressions (Boolean Expressions)

• Relational Expressions yield results of type bool which takes a value true or false.
• Ex:
• x<=y
• a+b==c+d
• m+n >100

Logical Expressions

• Logical expressions combine two or more relational expressions and produces bool type results.
• Ex:
• a>b && x==10
• x==10 || y=5

Bitwise Expressions

• Bitwise Expressions are used to manipulate data at bit level.
• They are basically used for shifting bits
• Ex:
• x<<3
• y>>1
Special Assignment Expressions
• Chained Assignment

p=(q=15); or p=q=15;

First 15 is assigned to q and then to p.

• Embedded Assignment

p=(q=50)+10;

(q=50) is an embedded assignment .

Here 50 is assigned to y and then the result 60 is assigned to x.

it is similar to q=50;

p=q+10;

Compound Assignment

C ++ supports a compound assignment operator which is a combination of assignment operator with a binary arithmetic operator.

a=a+10;

a+=10;

Evaluation of Expressions
• Expressions are evaluated using an assignment statement of the form:

variable=expression;

Precedence of operators

BODMAS RULE-

Brackets of Division Multiplication Addition Subtraction

Brackets will have the highest precedence and have to be

evaluated first, then comes of , then comes

division, multiplication, addition and finally subtraction.

The 2 distinct priority levels of arithmetic operators in c are-

Highest priority : * / %

Lowest priority : + -

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

• Associativity is used to determine the order in which operators with same precedence are evaluated in complex expression.
Example
• x=a-b/3+c*2-1
• When a=9,b=12,c=3,then statement becomes

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

In the first pass, the high priority operators are applied .

During the second pass, the low priority operators are applied.

First pass:

Step1: x=9-4+3*2-1

Step2: x=9-4+6-1

Second pass:

• step3: x=5+6-1
• Step4: x=11-1
• Step5: x=10
Rules for evaluation of expression
• First parenthesized sub expression from left to right are evaluated.
• If parentheses are nested, the evaluation begins with the innermost sub expression
• The precedence rule is applied in determining the order of application of operators in evaluating sub expressions
• The associatively rule is applied when 2 or more operators of the same precedence level appear in a sub expression.
• Arithmetic expressions are evaluated from left to right using the rules of precedence
• When parentheses are used, the expressions within parentheses assume highest priority
Example 1

Evaluate x1=(-b+ sqrt (b*b-4*a*c))/(2*a) @ a=1, b=-5, c=6

=(-(-5)+sqrt((-5)(-5)-4*1*6))/(2*1)

=(5 + sqrt((-5)(-5)-4*1*6))/(2*1)

=(5 + sqrt(25 -4*1*6))/(2*1)

=(5 + sqrt(25 -4*6))/(2*1)

=(5 + sqrt(25 -24))/(2*1)

=(5 + sqrt(1))/(2*1)

=(5 + 1.0)/(2*1)

=(6.0)/(2*1)

=6.0/2 = 3.0

Example 2

Evaluate the expression when a=4

b=a- ++a

=a – 5

=5-5

=0