• No results found

5-Operators.pdf

N/A
N/A
Protected

Academic year: 2020

Share "5-Operators.pdf"

Copied!
25
0
0

Loading.... (view fulltext now)

Full text

(1)

STRUCTURED

PROGRAMMING

(2)

Content

2

C++ operators

Assignment operators

Arithmetic operators

Increment and decrement operators

Decision making operators (logical and relational)

Conditional operator

Precedence and associativity of operators

(3)

Objectives

3

By the end you should be able to:

 Use the assignments and arithmetic operators

 How decisions are made in your programs

 Write simple decision –making statements

 Recognize the precedence and associatively of operators

 Identify and use the C++ conditional operator (?:)

 Identify and use Increment & decrement operators

 Use operators in output statements

(4)

Operators

 Data connectors within expression or equation

 Concept related

 Operand: data that operator connects and processes

 Resultant: answer when operation is completed

 Operators types based on their mission

 Assignment

 Arithmetic: addition, subtraction, modulo division, ...etc

 Relational: equal to, less than, grater than, …etc

 Logical (decision-making): NOT, AND, OR

(5)

Operators (cont.)

 Operators types based on number of operands

 Unary operators

 Have only one operand

 May be prefix or postfix

 e.g. -- ++ !

 Binary operators

 Have two operands

 Infix

 e.g. == && +

 Ternary operators

 Have three operands

 e.g. ? :

(6)

Assignment operators

 Assignment statement takes the form below

 Binary operators

 Expression is evaluated and its value is assigned to the variable on

the left side

 Shorthand notation

 varName = varName operator expression;

 varName operator = expression;

6

varName = expression;

c = c + 3;

(7)

Assignment operators (cont.)

 Assignment between objects of the same type is always supported

7

Assignment

operator Sample expression Explnation Assigns

Assume:

int c = 3, d = 5, e = 4, f = 6, g = 12;

+= c += 7 c = c + 7 10 to c

-= d -= 4 d = d – 4 1 to d

*= e *= 5 e = e * 5 20 to e

/= f /= 3 f = f / 3 2 to f

(8)

Arithmetic Operators

 All of them are binary operators

 Arithmetic expressions appear in straight-line form

 Parentheses () are used to maintain priority of manipulation

8

C++ operation C++ arithmetic

operator Algebraic expression C++ expression

Addition + f + 7 f + 7

Subtraction - p - c p - c

MUltiplication * bm or b . m b * m

Division / x / y or x ÷ y x / y

(9)

Arithmetic Operators Precedence

 Operators in parentheses evaluated first

 Nested/embedded parentheses

 Operators in innermost pair first

 Multiplication, division, modulus applied next

 Operators applied from left to right

 Addition, subtraction applied last

 Operators applied from left to right

(10)

Example

 The statement is written in algebra as

z = pr % q + w / (x – y)

 How can we write and evaluate the previous statement in C++ ?

z = p * r % q + w / (x - y);

10

5

3 4

2 1

(11)

Increment and Decrement Operators

 Unary operators

 Adding 1 to or (subtracting 1 from) variable’s value

 Increment operator gives the same result of

(c=c+1) or (c+=1)

 Decrement operator gives the same result of

(c=c-1) or (c-=1)

(12)

Increment and Decrement Operators (cont.)

12

Operator Called Sample expression

Explanation

++ Preincrement ++a Increment a by 1, then use the new value of

a in the expression in which a resides.

++ Postincrement a++ Use the current value of a in the expression

in which a resides, then increment a by 1.

 Pridecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.

(13)

Examples

13

int x = -10 , y;

y = ++x;

cout << “x = “ << x << endl;

cout << “y = “ << y << endl;

Example # 1

x = -9 y = -9

output # 1

int x = -10 , y;

y = x++;

cout << “x = “ << x << endl;

cout << “y = “ << y << endl;

Example # 2

x = -9 y = -10

(14)

Relational and Equality Operators

 Binary operators

 Used in decision -making statements

14

Standard algebraic equality operator or relational operator C++ equality or relational operator Example of C++ condition Meaning of C++ condition Relational operators

> > x > y x is greater than y

< < x < y x is less than y

 >= x >= y x is greater than or equal to y

<= x <= y x is less than or equal to y

Equality operators

= == x == y x is equal to y

(15)

Relational and Equality Operators (cont.)

 Have the same level of precedence

 Applied from left to right

 Used with conditions

 Return the value true or false

 Used only with a single condition

(16)

Logical Operators

 Used to combine between multiple conditions

&& (logical AND)

true if both conditions are true

gender == 1 && age >= 65

|| (logical OR)

true if either of condition is true

semesterAverage >= 90 || finalExam >= 90

16

(17)

Logical Operators (cont.)

! (logical NOT, logical negation)

 Returns true when its condition is false, and vice versa

!( grade == sentinelValue )

Also can be written as

grade != sentinelValue

(18)

Conditional operator (

?:

)

 Ternary operator requires three operands

 Condition

 Value when condition is true

 Value when condition is false

 Syntax

18

(19)

Examples

Can be written as

Can be written as .. ?

19

grade >= 60 ? cout<<“Passed” : cout<<“Failed”;

Example # 1

cout << (grade >= 60 ? “Passed” : “Failed”);

int i = 1, j = 2, Max; Max = ( i > j ? i : j );

(20)

Summary of Operator Precedence

and Associativity

20

Operators Associativity Type

() [] left to right highest

++ -- static_cast< type >( operand ) left to right unary (postfix)

++ -- + - ! & * right to left unary (prefix)

* / % left to right multiplicative

+ - left to right additive

<< >> left to right insertion/extraction

< <= > >= left to right relational

== != left to right equality

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment

(21)

bool

Variables in Expressions

 false is zero and true is any non-zero

 The following codes applies implicit conversion between bool and int

21

int x = -10 ;

bool flag = x ; // true

int a = flag ;

// assign the value 1

int b = !flag;

// assign the value 0

x = flag + 3;

// assign the value 4

bool test1,test2,test3 ;

int x = 3 , y = 6 , z = 4 ;

test1 = x > y ; // false

test2 = !(x == y ); // true

test3 = x < y && x < z ; // true

test3 = test1 || test2 ; // true

test2 = !test1; // true

(22)

Common Compilation Errors

 Attempt to use % with non-integer operands

 Spaces between pair of symbols e.g. (==, !=, …etc)

 Reversing order of pair of symbols e.g. =!

 Confusing between equality (==) and assignment operator (=)

(23)

Exercise - 1

23

What is the output of the following program?

1 #include <iostream> 2

3 using std::cout; 4 using std::endl; 5

6 int main() 7 {

8 int x; int y; int z; 9

10 x = 30; y = 2; z = 0; 11

12 cout << (++++x && z ) << endl; 13 cout << x * y + 9 / 3 << endl; 14 cout << x << y << z++ << endl; 15

16 return 0; 17

(24)

Exercise - 2

24

What is wrong with the following program?

1 int main() 2 {

3 int a,b,c,sum; 4 sum = a + b + c ;

5 return 0;

(25)

Included Sections

25

References

Related documents

Should We Stay or Should We Go?: A Study of Indian IT Migrants Should We Stay or Should We Go?: A Study of Indian IT Migrants in Raleigh-Durham, North Carolina: Deciding to Stay

Validation of Analysis Method α-Mangostin Compound on Skin Fruit Extract Kandis Acid ( Garcinia iowar Rob. Ex Choisy) Method HPLC.. Roslinda Rasyid 1 , Fitra Fauziah 2 ,

Generally, the nodes are the active mode in the network, which consume more energy (i.e. crucially more amount of the energy is wasted) than the energy expenditure for

No compound found to have measurable activity against Candida albicans but some compounds (32a-32f) were found to be effective against Trichophyton mentagrophytes (Fig. Bharat

A novel, efficient, and effective refined histogram for modeling the Discrete Wavelet Transform (DWT) decomposed sub-band detail coefficients and a new image signature based on

[r]

Should any of the required insurance be provided under a claims-made form, Contractor shall maintain such coverage continuously throughout the term of this Agreement and,

However, for incidents in cyber-physical systems, this is not sufficient due to the interactions between cyber and physical components that are often exploited (e.g.,