54
OPERATORS

OPERATORS. What are operators? In c++ the operators are mostly made of signs. It relies less on English words. They are to perform specific tasks on the

Embed Size (px)

Citation preview

OPERATORS

What are operators?

In c++ the operators are mostly made of signs. It relies less on English words. They are to perform specific tasks on the operands.

Classification of Operators

No of OperandsUnary Operators Binary OperatorsTernary Operators

Type of operationsArithmatic OperatorsRelational OperatorsLogical Operators

The operators can be classified based on

Classification of Operators (No of Operands)

Operand is constant or variable used by the operator.

Binary Operators : These are the operators that act on two operands.

Unary Operators : These are the operators that act on one operand.

Ternary Operators : These are the operators that act on three operands.

Classification of Operators (Type of Operation)

Based on the type of operations the operators are classified as

Arithmatic Operators : These operators give results in numeric form

Relational Operators : These operators give results in form of true/false.

Logical Operators : These operators too give result in true/false form.

ARITHMATIC OPERATORS

Assignment Operator (=)

The assignment operator assigns a value to a variable.

The assignment operation always takes place from right to left, and never the other way:

E.g. x=5;

This statement assigns the integer value 5 to the variable a.

5=x; // is wrong

Take a look at this example // assignment operator #include <iostream>using namespace std;int main (){ int a, b; // values of a & b are unknown a = 10; // a=10 & value of b is unknown b = 4; // a=10, b=4 a = b; // a=4, b=4 b = 7; // a=4, b=7 cout << "a:"; cout << a; cout << " b:"; cout << b; return 0;}

OUTPUT

Can you predict output of the program?

The output will be

a:4b:7

Notice how a was not affected by the final modification of b, even though we declared a = b earlier (that is because of the right-to-left rule).

Assignment Operator

Assignment operator can be chained together.

E.g.

A = B = C = 10;

Variables can be intialised by means of assignment operator only.

E.g.

A = B = C = 10;

E.g.

int a = 10;

ARITHMATIC OPERATORS

UNARY + : The operator unary + precedes an operand. The operand must be arithmatic or pointer.

E.g.

If a=8 then +a means 8If a=-2 then +a means -2

UNARY - : The operator unary + precedes an operand. The operand must be arithmatic.

E.g.

If a=8 then -a means -8If a=-2 then -a means 2

ARITHMATIC OPERATORS

Addition/subtraction/multiplication/division : These are binary operators. The operands for these operators may be integer or float type.

E.g.

If a = 10 and b = 5 a+b results in 15 a-b results in 5 a*b results in 50 a/b results in 2

DIVIDE BY ZERO

! Care should be taken to avoid 'divide by zero' error which is caused if in a/b, b=0.

e.g.

cout <<3/0; // This statement will cause 'Divide by Zero' error.

ARITHMATIC OPERATORS

Modulus operator (%) : Its result is the remainder of dividing the first operand by second. Both operands must of integer type.

E.g.

19%6 results in 10%3 results in 0

Increment/ Decrement Operators(++/--)

These are the special operators available in c and c++ languages.

This operator increases or decreases value of variable by 1.

A characteristic of the operator is that it can be prefixed or suffixed.

Thus it can be written as ++a or a++.

!ImportantIt is important to note that a postfix increment or decrement expression evaluates to the value of the expression prior to application of the respective operator.

The increment or decrement operation occurs after the operand is evaluated.

This issue arises only when the postfix increment or decrement operation occurs in the context of a larger expression.

Thus ,

a++; ++a; Both will work exactly same way

Let us see what it means.

Example 1

b=3; a=++b;cout << “a=”<<a<<” b=”<<b;

Example 2

b=3; a=b++;cout << “a=”<<a<<”--b=”<<b;

a=? b=3

a=4 b=4

a=? b=3

a=3 b=4

Output

a=4 b=4

Output

a=3 b=4

! NOTE

The postfix increment or decrement operator follows use and then change rule.

The prefix increment or decrement operator follows change and then use rule.

Try solving Worksheet 1 at this point.

The postfix operator has higher precedence than prefix. So postfix operators will get evaluated before prefix.

RELATIONAL OPERATORS

Relational Operators

These operators determine the relation between the operands. The result of relational operators is in form of true(1) or false(0).

Operator Meaning

< Less Than

> Greater Than

<= Less Than or equal to

>= Greater Than or equal to

== Equal to

!= Not equal to

! NOTE

Avoid equality comparison on floating point numbers.

Do not confuse between = (assignment operator) and == (equal to operator)

Avoid equality comparison between signed and unsigned values.

Observe the program

int main() { cout << "The true expression 3 > 2 yields: " << (3 > 2) << endl; cout << "The false expression 20 < 10 yields: "<< (20 < 10) ; return 0;}

Output

The true expression 3>2 yields: 1The false expression 20<10 yields : 0

Observe this program

int main() { int x;

cin >> x; if (x=5) cout <<”Hello”<<endl; else cout << “Good Bye”<<endl;

return 0; }

What will be the output, if.....

x=5 x=7

Case 1 Case 2

The output will be

Hello

The output will be

Hello

Can you tell why?

Reason

C++ considers 0 as a false and any non-zero value as true.

x=5 will always evaluate to 5 as the operator used is assignment operator.5 being a true value the code will always display 'Hello'

x==5 will compare value of x with 5 and evaluate to true or false.

LOGICAL OPERATORS

Logical Operators

C++ provides three logical operators to combine existing expressions.

Logical OR : Represented by || symbol.

Logical AND : Represented by && symbol.

Logical NOT : Represented by ! symbol.

Logical OR

The logical OR is binary operator that takes two expressions to connect. It is evaluated using following truth table.

EXP 1 EXP 2 RESULTF F FF T TT F TT T T

E.g.(5 > 3) || ( 8 < 3)

T || F

T

Logical AND

The logical AND is binary operator that takes two expressions to connect. It is evaluated using following truth table.

EXP 1 EXP 2 RESULT

F F F

F T F

T F F

T T T

E.g.(5 > 3) && ( 8 < 3)

T && F

F

Logical NOT

The logical NOT is unary operator that takes one expressions to negate it. It is evaluated using following truth table.

EXP 1 RESULT

F T

T F

E.g.!(5 > 3)

! T

F

CONDITIONAL OPERATOR (? :)

Only ternary operator of c++ language. It is written as follows,

Exp1 ? Exp2 : Exp3

If expression1 evaluates to True then the whole expression evaluates to expression 2 else the whole expression evaluates to expression 3.

Consider following code snippet

char grade;int marks;

grade = marks >= 500 ? 'P' : 'F';

cout << grade;

Output will be

P if marks are greater than or equal to 500

F if marks are not greater than or equal to 500

Consider following code snippet

int x,y;float value;

cin >> value;value > 500 ? x : y =10;

! NOTE : Conditional operator is allowed on the left side of an expression.

x will be 10 if value is greater than 500, else y will be 10.

Some Other Operators

sizeof ( ) : This is compile time operator that evaluates to number of bytes occupied by variable or date type specified in parenthesis.

E.g.

cout << sizeof(char);

Will display 1

E.g.

char ch;cout << sizeof(ch);

Will display 1

COMMA OPERATOR

It is used to string together several expressions.

It is evaluated from left to right.

E.g.

b=(a=3,a+1);

First a get value 3 then b gets value a+1.

CHECK POINT

SOLVE WORKSHEET 2 TO SEE IF YOU HAVE UNDERSTOOD WHAT WE HAVE DONE TILL NOW.

PRECEDENCE OF OPERATORSHIGHEST ++ (Post increment), -- (Post decrement)

++ (Pre increment), -- (Pre decrement), !, +(unary plus), - (unary minus), sizeof

*(multiply), / (divide), % (modulus)

+(add), - (subtract)

< (less than), >(greater than), <=(less than or equal to), >=(greater than or equal to)

== (equal), != (not equal)

&& (l)ogical AND)

|| (logical OR)

? : (Conditional Operator)

= (assignment)

LOWEST , (Comma operator)

Expression Evaluation

Let us see how the expressions get evaluated.

F = ++A / B - A A = 5, B = 2

A = 6, B = 2 F = ++A / B - A

F = 6 / B - A A = 6, B = 2

F = 6 / 2 - A A = 6, B = 2

F = 3 - A A = 6, B = 2

F = 3 - 6 A = 6, B = 2

F = -3 A = 6, B = 2

! NOTE : When more than one operator of same predecence is there evaluation is done from left to right.

Expression Evaluation

Let us see how the expressions get evaluated.

F = A ++ / B - A A = 5, B = 2

A = 5, B = 2 F = A++ / B - A

F = 5 / B - A A = 6, B = 2

F = 5 / 2 - A A = 6, B = 2

F = 2.5 - A A = 6, B = 2

F = 2.5 - 6 A = 6, B = 2

F = -3.5 A = 6, B = 2

! NOTE : When more than one operator of same predecence is there evaluation is done from left to right.

CHECK POINT

SEE IF YOU CAN EVALUATE EXPRESSIONS BY USING CORRECT PRECEDENCE OF OPERATOR.

TRY AND SOLVE WORKSHEET 3

Expressions

An expression in C++ is any series of tokens that, when it is evaluated and all commands contained within it are run, is equivalent to a value.

For instance, a + b is an expression, as are 35902 and "Hello world!". An expression is said to “evaluate to” its value.

This is in contrast to a statement, such as x = a + b;, which gives an instruction to the processor.

TYPES OF EXPRESSION

# Arithmatic expressions.

# Logical expressions

# Expressions with explicit type conversions.

# Expression with implicit type conversions.

CHECK POINT

TRY AND SEE IF YOU CAN IDENTIFY EXPRESSIONS.SOLVE WORKSHEET 4

Parts of Expression

There are two different parts of expressions:

L-values : An L-value appears on the left side of an assignment statement (“L” for “left”); it is the thing that is assigned to.

R-values : An R-value is the expression whose value is evaluated, and possibly assigned to an L-value.

For example, in the statement x = y + 5;, x and y are both identifiers; x is an L-value; and y, 5, and y + 5 are all R-values.

Valid Expressions

a/b 2 * x + y sqrt(b *a) log(2) *3 3 % 2 p / q * r - t

These are examples of valid expressions.

e >= g (x>y) && (y>z)

Invalid Expressions

a/ *b 2x + y sqrt(-a) log(-2) *3 3.5 % 2

These are examples of invalid expressions.

Some Mathematical Functions to write expressions

Include math.h header file if you are going to use any of these functions.

Function Prototype Description

ceil double ceil( double)Returns smallest integer not less than parameter.

exp double exp(double)Return the

logarithmic e to the arg power.

pow double pow(double base, double exp)

Returns base raise to exp

sin double sin (double arg)

Returns sine of arg, where arg is angle in radian.

Some Mathematical Functions to write expressions

Include math.h header file if you are going to use any of these functions.

Function Prototype Description

cos double cos( double arg)

Returns cos of arg, where arg is angle in radian.

tan double tan(double arg)

Returns tan of arg, where arg is angle in radian.

fabs double fabs(double num)

Returns absolute value of num

log double log (double num)

Returns natural logarithm of the num

TYPE CONVERSION

The conversion of one predefined type to another is called type conversion.

There are two types of conversion

Implicit Type Conversion Explicit Type Conversion (Type Casting)

Type Conversion Hierarchy

HIGHEST Long double

double

floatUnsigned long int

long

Unsigned int

LOWEST int

This means that if an expression is have different types of operands then the resultant operand would have type that is higher in hierarchy.

TYPE CONVERSION

E.g. Take following example

2 + 3.14

One operand is of int type and other is float. As float is higher up in hierarchy the resultant type will be float.

The result will be 5.14

Explicit Type Conversion

Explicit conversion is user-defined. That forces the expression to be of specific type.

It is also called type casting.

E.g.

(float)(x+y/2)

This will force the result to be floating point value

C++ SHORTHANDSC++ offers special shorthands that simplify coding.

Normal Expression Shorthand Expression

X = X + 10 X += 10

X = X - 10 X -= 10

X = X * 10 X *= 10

X = X / 10 X /= 10

X = X % 10 X %= 10

CHECK POINT

Evaluate your understanding of the chapter by solving Worksheet 5.