Download presentation
Presentation is loading. Please wait.
Published byGeorgia Griffith Modified over 9 years ago
1
Section 3 - Selection and Repetition Constructs
2
Control Structures 1. Sequence 2. Selection 3. Repetition
3
Selection – choosing between alternatives
4
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
5
Relational Expressions Result is a Boolean value – true or false Examples: 12 > 5 is true 7 <= 5 is false if x is 10, then x == 10 is true x != 8 is true x == 8 is false
6
Examples int i = 5; int k = 12; bool p = (i < 10); bool q = (k > i); bool r = (i >= k); bool s = (k <= 12);
7
Comparison Operators
8
Relational Expressions Can be assigned to a variable result = x <= y; Assigns 0 for false, 1 for true Do not confuse = and ==
9
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.” Syntax if (expression) statement;
10
if statement – what happens To evaluate if (expression) statement; If (expression) is true, then statement is executed. If (expression) is false, then statement is skipped – not executed
11
if statement – what happens expression statement expression is true expression is false
12
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
13
Example if (radius >= 0) { area = radius * radius * PI; cout << "The area for the circle of " << " radius " << radius << " is " << area; }
14
The if/else Statement Allows choice between statements if (expression) is true or false Syntax if (expression) statement1; // or block else statement2; // or block
15
if/else – what happens expression statement1 expression is true expression is false statement2
16
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';
17
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;
18
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”
19
if/else/if format if (expression) statement1; // or block else if (expression) statement2; // or block.. // other else ifs. else if (expression) statementn; // or block
20
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; }
21
Example
22
The switch Statement Used to select among statements from several alternatives May be used instead of if/else if statements
23
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!; }
24
switch statement format switch (expression) //integer { case exp1: statement1; case exp2: statement2;... case expn: statementn; default: statementn+1; }
25
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”
26
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.
27
switch statement – how it works 1.expression is evaluated 2.The value of expression is compared against exp1 through expn. 3.If expression matches value expi, the program branches to the statement(s) following expi Note: 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
28
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
29
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; }
30
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; }
31
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
32
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
33
Common Error 1: Forgetting Necessary Braces
34
Common Error 2: Wrong Semicolon at the if Line
35
Common Error 4: Redundant Testing of Boolean Values
36
Common Error 3: Mistakenly Using = for == if (count = 1) cout << "count is zero" << endl; else cout << "count is not zero" << endl;
37
Repetition - looping
38
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
39
The while Loop Loop: a statement or set of statements that may execute more than one time (repeats) Syntax while (expression) statement; Will execute statement repeatedly while expression evaluates to true statement can also be a block of statements enclosed in { }
40
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
42
Example int count = 0; while (count < 100) { cout << "Welcome to C++!\n"; count++; }
43
while Loop Example int val = 5; while (val <= 8) cout << val++ << endl; produces output: 5 6 7 8
44
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
45
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++; }
46
The do-while Loop do-while: a post-test loop – execute the loop, then test the expression Syntax do statement; // or block in { } while (expression); Note ; after (expression)
47
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
48
Statement(s) true false Expression
50
for Loop Useful for counter-controlled loop Syntax for (initialization; test; update) statement; // or block in { } Or, re-stated with a counter variable for (i = initialValue; i < endValue; i++) statement; // or block in { }
52
int i; for (i = 0; i < 100; i++) { cout << "Welcome to C++!\n"; } Example
53
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;
54
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";
55
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.
56
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
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.