section 3 - selection and repetition constructs. control structures 1. sequence 2. selection 3....

56
ction 3 - Selection and Repetition Construct

Upload: georgia-griffith

Post on 23-Dec-2015

260 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Section 3 - Selection and Repetition Constructs

Page 2: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Control Structures

1. Sequence

2. Selection

3. Repetition

Page 3: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Selection – choosing between alternatives

Page 4: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Relational Operators

• Used to compare numbers, characters and strings to determine relative order

• Operators:

> Greater than< Less than>= Greater than or equal to<= Less than or equal to== Equal to!= Not equal to

Page 5: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Relational Expressions

• Result is a Boolean value – true or false

• Examples:12 > 5 is true7 <= 5 is false

if x is 10, then x == 10 is true x != 8 is true x == 8 is false

Page 6: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Examples

int i = 5;

int k = 12;

bool p = (i < 10);

bool q = (k > i);

bool r = (i >= k);

bool s = (k <= 12);

Page 7: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Comparison Operators

Operator Name Example Result

< less than 1 < 2 true

<= less than or equal to 1 <= 2 true

> greater than 1 > 2 false

>= greater than or equal to 1 >= 2 false

== equal to 1 == 2 false

!= not equal to 1 != 2 true

Page 8: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Relational Expressions

• Can be assigned to a variableresult = x <= y;

• Assigns 0 for false, 1 for true

• Do not confuse = and ==

Page 9: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

The if Statement

• Allows statements to be conditionally executed or skipped over

• Models the way we mentally evaluate situations– “If it is raining, take an umbrella.”

• Syntaxif (expression)

statement;

Page 10: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

if statement – what happens

To evaluateif (expression)

statement;

• If (expression) is true, then statement is executed.

• If (expression) is false, then statement is skipped – not executed

Page 11: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

if statement – what happens

expression

statement

expressionis true

expressionis false

Page 12: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Expanding the if Statement

• To execute more than one statement as part of an if statement, enclose them in { }

if (score > 90){

grade = “Excellent”;cout << “Well done!\n";

}

• { } creates a block of code

Page 13: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Example

if (radius >= 0) { area = radius * radius * PI; cout << "The area for the circle of " << " radius " << radius << " is " << area;}

Page 14: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

The if/else Statement

• Allows choice between statements if (expression) is true or false

• Syntaxif (expression)

statement1; // or blockelse

statement2; // or block

Page 15: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

if/else – what happens

expression

statement1

expressionis true

expressionis false

statement2

Page 16: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Example

if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';

Page 17: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Finding the Max

cout << "Enter two integers: ";int Value1;int Value2;cin >> Value1 >> Value2;

int Max;if (Value1 < Value2) { Max = Value2;}else { Max = Value1;}cout << "Maximum of inputs is: " << Max << endl;

Page 18: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

The if/else/if Statement

• Chain of if statements that test in order until one is found to be true

• Also models thought processes:– “If it is raining, take an umbrella,

else, if it is windy, take a hat, else, take sunglasses”

Page 19: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

if/else/if format

if (expression) statement1; // or block

else if (expression) statement2; // or block . . // other else ifs .

else if (expression) statementn; // or block

Page 20: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

An If-Else-If Statement

if ( nbr < 0 ){ cout << nbr << " is negative" << endl;}else if ( nbr > 0 ) { cout << nbr << " is positive" << endl;}else { cout << nbr << " is zero" << endl;}

Page 21: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Example

Page 22: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

The switch Statement

• Used to select among statements from several alternatives

• May be used instead of if/else if statements

Page 23: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

switch Statement

switch (weather) { // sunny case 0: take sunglasses; break; // windy case 1: take hat; break; // rainy case 2: take umbrella; break; // not any of the above default: flip a coin!;}

Page 24: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

switch statement format

switch (expression) //integer{

case exp1: statement1;case exp2: statement2;...case expn: statementn;default: statementn+1;

}

Page 25: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

switch statement requirements

1) expression must be an integer or char variable, or an expression that evaluates to an integer value

2) exp1 through expn must be constant integer expressions or literals, and must be unique in the switch statement

3) default is optional but recommended “catch-all”

Page 26: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.

switch (switch-expression) {

case value1: statement(s)1;

break;

case value2: statement(s)2;

break;

case valueN: statement(s)N;

break;

default: statement(s)-for-default;

}

The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression.

The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.

Page 27: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

switch statement – how it works

1. expression is evaluated2. The value of expression is compared against exp1 through

expn. 3. If expression matches value expi, the program branches to the

statement(s) following expiNote: Must “break out”of switch construct after statement(s)executed.

4. If no matching value is found, the program branches to the statement after default

Page 28: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

break statement

• Used to stop execution in the current block

• Also used to exit a switch statement

• Useful to execute a single case statement without “falling through” and executing the statements following it

Page 29: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Example

switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch;}

If ch equals ‘a’, what happens?

switch (ch) { case 'a': cout << ch; break; case 'b': cout << ch; break; case 'c': cout << ch;}

Page 30: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

A Switch Statement

switch (ch) {

case 'a': case 'A':

case 'e': case 'E':

case 'i': case 'I':

case 'o': case 'O':

case 'u': case 'U':

cout << ch << " is a vowel" << endl;

break;

default:

cout << ch << " is not a vowel" << endl;

}

Page 31: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

cout << "Enter simple expression: ";

int Left;

int Right;

char Operator;

cin >> Left >> Operator >> Right;

cout << Left << " " << Operator << " " << Right

<< " = ";

switch (Operator) {

case '+' : cout << Left + Right << endl; break;

case '-' : cout << Left - Right << endl; break;

case '*' : cout << Left * Right << endl; break;

case '/' : cout << Left / Right << endl; break;

default: cout << "Illegal operation" << endl;

}

Example

Page 32: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Logical Operators - examples

int x = 12, y = 5, z = -4;

(x > y) && (y > z) true

(x > y) && (z > y) false

(x <= z) || (y == z) false

(x <= z) || (y != z) true

!(x >= z) false

Page 33: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Common Error 1: Forgetting Necessary Braces

if (radius >= 0) area = radius * radius * PI; cout << "The area " << " is " << area;

(a) Wrong

if (radius >= 0) { area = radius * radius * PI; cout << "The area " << " is " << area; } (b) Correct

Page 34: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Common Error 2: Wrong Semicolon at the if Line

if (radius >= 0); { area = radius * radius * PI; cout << "The area " << " is " << area; } (a)

Equivalent

Logic Error

if (radius >= 0) { }; { area = radius * radius * PI; cout << "The area " << " is " << area; } (b)

Empty Body

Page 35: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Common Error 4: Redundant Testing of Boolean Values

if (even == true) cout <<"It is even.";

(a)

Equivalent if (even) cout << "It is even.";

(b) This is better

Page 36: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Common Error 3: Mistakenly Using = for ==

if (count = 1) cout << "count is zero" << endl;else cout << "count is not zero" << endl;

Page 37: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Repetition - looping

Page 38: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Suppose that you need to print a string (e.g. "Welcome to C++!") a hundred times.

- It would be tedious to have to write the following statement a hundred times:

cout << "Welcome to C++!" << endl;

So, how do you solve this problem?

Answer: Use one of the three looping constructs available

Page 39: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

The while Loop

• Loop: a statement or set of statements that may execute more than one time (repeats)

Syntaxwhile (expression)

statement;

Will execute statement repeatedly while expression evaluates to true

• statement can also be a block of statements enclosed in { }

Page 40: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

while Loop

• no ; after (expression)

• while is a pre-test loop – expression is evaluated before the loop executes

• Loop may not be executed at all! – pre-test

• loop must contain code to make expression become false

• Infinite loop: loop that does not stop

Page 41: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition
Page 42: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Example

int count = 0;while (count < 100) { cout << "Welcome to C++!\n"; count++;}

Page 43: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

while Loop Example

int val = 5;while (val <= 8)

cout << val++ << endl;

produces output:5678

Page 44: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Counters

• Counter: variable that is incremented or decremented each time a loop repeats

• Can be used to control execution of the loop (called a loop control variable)

• Must be initialized before entering loop

• May be incremented/decremented either inside the loop or in the loop test

Page 45: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Letting the User Control a Loop

int num = 1, limit;cout << "Table of squares\n";cout << "How high to go? ";cin >> limit;cout << "number square\n";while (num <= limit){ cout << num <<“ “ << num*num << endl;

num++;}

Page 46: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

The do-while Loop

• do-while: a post-test loop – execute the loop, then test the expression

Syntaxdo

statement; // or block in { } while (expression);

• Note ; after (expression)

Page 47: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

do-while Loop

• Loop always executes at least once – post-test

• Execution continues as long as expression is true, stops repetition when expression becomes false

• Useful in menu-driven programs to bring user back to menu to make another choice

Page 48: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Statement(s)

true

false

Expression

Page 49: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Loop Continuation Condition?

true

Statement(s) (loop body)

false

Page 50: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

for Loop

• Useful for counter-controlled loop

Syntaxfor (initialization; test; update)

statement; // or block in { }

Or, re-stated with a counter variable

for (i = initialValue; i < endValue; i++) statement; // or block in { }

Page 51: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition
Page 52: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

int i;for (i = 0; i < 100; i++) { cout << "Welcome to C++!\n";}

Example

Page 53: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

for Loop - Example

int sum, num;

for (sum=0, num=1; num <= 10; num++)sum += num;

cout << "Sum of numbers 1 through 10 is" << sum << endl;

Page 54: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Nested Loops

• A nested loop is a loop inside the body of another loop

• Inner (inside), outer (outside) loops

Example

if (i > k) { if (j > k) cout << "i and j are greater than k";}else cout << "i is less than or equal to k";

Page 55: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Example

for (row=1; row<=3; row++) //outer

for (col=1; col<=3; col++) //inner

cout << row * col << endl;

For each repetition of outer loop, inner loop is executed 3 times.

Page 56: Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition

Nested Loops

• Inner loop goes through all repetitions for each repetition of outer loop

• Inner loop repetitions complete sooner than outer loop

• Total number of repetitions for inner loop is product of number of repetitions of the two loops.

• In previous example, inner loop repeats 9 times