22
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage do dishes if you have less than $100 visit the bank withdraw $100 – cash on hand endif drive to Loblaws if potatoes are less than 20 cents a pound buy 10 pounds of potatoes else buy 5 pounds of carrots buy some lettuce endif drive to the LCBO etc. Do only if the “condition ” is true. Do one or the other of these actions.

If’s – The Basic Idea

  • Upload
    paco

  • View
    44

  • Download
    1

Embed Size (px)

DESCRIPTION

If’s – The Basic Idea. “Program” for hubby: take out garbage do dishes if you have less than $100 visit the bank withdraw $100 – cash on hand endif drive to Loblaws if potatoes are less than 20 cents a pound buy 10 pounds of potatoes else buy 5 pounds of carrots - PowerPoint PPT Presentation

Citation preview

Page 1: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1

If’s – The Basic Idea

“Program” for hubby:

take out garbagedo dishesif you have less than $100 visit the bank withdraw $100 – cash on handendifdrive to Loblawsif potatoes are less than 20 cents a pound buy 10 pounds of potatoeselse buy 5 pounds of carrots buy some lettuceendifdrive to the LCBOetc.

Do only if the “condition” is true.

Do one or the other of these actions.

Page 2: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 2

Basic If Flowchart

if (true or false expression) { < statements>}

TestCondition

ExecuteStatements

Is true

Is false

Page 3: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 3

If .. Else Flowchart

if (true or false expression) { < true part statements>} else { <false part statements>}

TestCondition

ExecuteTrue Part

Is falseIs true

ExecuteFalse Part

Page 4: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 4

Bool

“Bool” is a new type (like “int” and “double” except in that we’re dealing with a different kind of values).

int: possible values = 0, 1, 2, -9, etc.

double: possible values = 0.0. 0.2, -5.6. etc.

bool: possible values = true, false

“True” and “false” are bool constants, just as 0 is an int constant and 4.3 is a double constant.

We can have bool variables, just as we can have int and double variables.

Note: if you have an older compiler which doesn’t recognize “bool”, place the following after your include directives:

typedef enum { false = 0, true = 1} bool;

Page 5: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 5

C++ Basic If Details

Basic If Statement:

if (boolean expression) { any number of statements }

“boolean expression” is an expression which evalauates to a bool value (e.g. either “true” or “false”). It will often involve “relational” operators (next slide) which compare two values and produce a true/false result.

The above format is actually the combination the fundamental C++ if statement (which allows only one statement to be conditionally executed) and the C++ “block statement” (which bundles a number of statements together). If this makes sense (see the text for details), fine. Otherwise just pretend that the fundamental if statement is as shown above.

Page 6: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 6

Relational Operators

< is less than> is greater than<= is less than or equal to>= is greater than or equal to== is equal to!= is not equal to

These operators compare two “arithmetic” (int or double) values and produce a bool result.

Precedence Operators AssociativityHighest unary - Right

cast Right

* / % Left

binary - + Left

< > <= => Left

Lowest == != Left

Page 7: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 7

Sample If Program

// include’s omitted

void main (void) {

int a, b, temp;

cout << “Please enter two values: “; cin >> a >> b;

if (a > b) { // the standard way of swapping values temp = a; a = b; b = temp; }

cout << “The values in order are “ << a << “ and “ << b << endl;

} // end main

Page 8: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 8

Bool Conversions (1)

C++ is (unfortunately) very generous in letting us use bool values in situations which require a arithmetic value (and vice versa). It is permissable, for example, to assign a bool value to an int variable, or to add two bools.

Rule 1: If a bool value is used in a situation where an arithmetic value is required, the bool value is automatically converted to int.

- false is converted to zero - true is converted to a non-zero value (normally 1)

Rule 2: If an arithmetic value is used in a situation where a bool value is required, the arithmetic value is automatically converted to bool.

- zero is converted to false - non-zero values are converted to true

Page 9: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 9

Bool Conversions (2)

These automatic conversions are of little if any practical value, and C++ would be a better language is they weren’t performed. They are essentially an unfortunate legacy of the history of C and C++, and result in two very nasty pitfalls for the unwary.

int a = 4, b = 20;

if (5 < a < 8) { // we will get here (surprise 1) . . . }

if (b = 16) { // note missing second ‘=‘ // we will get here (surprise 2) . . . }

Page 10: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 10

C++ If..else Details

If..Else Statement:

if (boolean expression) { any number of statements } else { any number of statements }

“boolean expression” is an expression which evalauates to a bool value.

The above format is actually the combination the fundamental C++ if..else statement (which allows only one statement in each of the true and false parts executed) and two block statements. If this makes sense (see the text for details), fine. Otherwise just pretend that the fundamental if statement is as shown above.

Page 11: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 11

Sample If..Else Program

// include’s omitted

void main (void) {

int a, b, largest;

cout << “Please enter two values: “; cin >> a >> b;

if (a >= b) { largest = a; } else { largest = b; }

cout << “The largest of the values is “ << lasrgest << endl;

} // end main

Page 12: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 12

Nested If’s

The statements inside an if may include further if statements. This is known as “nested if’s”.

void main (void) {

int a, b; cout << “Please enter two values: “; cin >> a >> b;

if (a < b) { cout << “The 1st value is smaller.” << endl; } else { if (a > b) { cout << “The 1st value is bigger.” << endl; } else { cout << “The values are equal.” << endl; } }

} // end main

Page 13: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 13

Quadratic Example (1)

A “quadratic” is an equation of the form:

ax2 + bx + c = 0

where “a”, “b”, and “c” are constants.

Example: 2x2 – 11x + 15 = 0

In general, quadratics have two solutions (known as the “roots”). In the example given, “x” may be either 2.5 or 3.

2(2.5)2 – 11(2.5) + 15 = 13.5 – 28.5 + 15 = 0

2(3)2 – 11(3) + 15 = 18 – 33 + 15 = 0

a is 2 b is –11 c is 15

Page 14: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 14

Quadratic Example (2)

The formula for the roots is as follows:

If the discriminant is negative there are no real roots (because we can’t take the square root of a negative value).

If the discriminant is zero there is only one root (because we get the same answer whether we add or subtract the square root).

Otherwise there are two roots.

See sample program quad.cpp.

-b +/- b2 – 4ac

2a

“discriminant”

Page 15: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 15

C++ Multi-way If

Multi-way If Statement:

if (boolean expression) { any number of statements } else if (boolean expression) { any number of statements } else if (boolean expression) { any number of statements . . . } else { // the else part is optional any number of statements }

The statements associated with the first true expression are executed. If no conditions are true, the statements in the else part (if there is one) are executed.

Not a fundamental C++ statement (just a way of combining if..else and block statements).

Page 16: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 16

Multi-way If Example

if (discriminant < 0) { // no real solutions cout << . . .} else if (discriminant == 0) { // one solution solution_1 = . . . cout << . . .} else { // two solutions solution_1 = . . . solution_2 = . . . cout << . . .}

Neater and easier to follow than the nested if’s used in the first quadratic sample program, and reflects the fact that we’re dealing with a three-way choice.

See sample program quad-m.cpp.

Page 17: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 17

Logical Operations

AND – result is true if both operands are true.

if it is sunny AND you have money visit the beach

we are to visit the beach only if it is sunny and we also have some money.

OR – result is true if either operand is true.

if you have cash OR you have a credit card go shopping

we are to go shopping if we have either some cash or a credit card.

NOT – result is true if the operand is false.

if NOT you have money drop by the bank

we are to drop by the bank if we don’t have any money

Page 18: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 18

Logical Operators

&& AND|| OR! NOT

These operators operate on bool values and produce bool results.

Precedence Operators AssociativityHighest unary - ! (not) Right

casts Right

* / % Left

binary - + Left

< > <= => Left

== != Left

&& (and) Left

Lowest || (or) Left

Page 19: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 19

Logical Operators Example (1)

Checking that the latitude and longitude entered by the user are valid . . .

cin >> lat_1 >> lng_1;if ( (lat_1 > 90.0) || (lat_1 < -90.0) || (lng_1 > 180.0) || (lng_1 < -180.0) ) { // input is invalid cout << “. . .”; return; // in main = “stop”}

The boolean expression evaluates to true if the input is invalid and to false otherwise.

If main is declared as “int main”, the return statement must include a value. By convention a non-zero value is used when stopping because of an error.

Page 20: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 20

Logical Operators Example (2)

The same effect can be achieved (if in a less intuitive way) using AND and NOT.

cin >> lat_1 >> lng_1;if ( !( (lat_1 <= 90.0) && (lat_1 >= -90.0) && (lng_1 <= 180.0) && (lng_1 >= -180.0) ) ) { // input is invalid cout << “. . .”; return; // in main = “stop”}

The boolean expression within !(. . .) evaluates to true if the input is valid and to false otherwise. The ! flips true to false and vice versa, making the whole expression true if the input is invalid and false otherwise.

This is an example of “deMorgan’s Law”.

Page 21: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 21

Triangle Example (1)

We want a program which will read in three values and output whether or not they represent a triangle (e.g. 3, 4, and 5 represent a triangle, but 1, 10, and 2 don’t). If the values do in fact represent a triangle, the program is also to output the angles of the triangle (in degrees) and whether or not any of them exceed 90 degrees.

A

B

C

ca

b

Cos A = ((b2 + c2) – a2) / 2bc

Page 22: If’s – The Basic Idea

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 22

Triangle Example (2)

Three values do not represent a triangle if any one of them is greater than or equal to the sum of the other two. In the diagram below, “b” exceeds the sum of “a” and “c”.

a c

b

cout << “. . .”;cin >> a >> b >> c;

if ( (a >= (b + c)) || (b >= (a + c)) || (c >= (a + b)) ) { // we don’t have a triangle . . .} else { // we do have a triangle . . .}

See sample program triang.cpp.