1 / 22

# If’s – The Basic Idea - PowerPoint PPT Presentation

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

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

## PowerPoint Slideshow about ' If’s – The Basic Idea' - paco

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

“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

else

endif

drive to the LCBO

etc.

Do only if the “condition” is true.

Do one or the other of these actions.

if (true or false expression) {

< statements>

}

Test

Condition

Is false

Is true

Execute

Statements

if (true or false expression) {

< true part statements>

} else {

<false part statements>

}

Test

Condition

Is true

Is false

Execute

True Part

Execute

False Part

“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;

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.

< 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.

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

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

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)

. . .

}

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.

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

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

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

-b +/- b2 – 4ac

2a

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.

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).

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.

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

&& AND

|| OR

! NOT

These operators operate on bool values and produce bool results.

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.

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”.

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.

B

c

a

A

C

b

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

c

b

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”.

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.