Presentation is loading. Please wait.

Presentation is loading. Please wait.

2.6 The if/else Selection Structure

Similar presentations


Presentation on theme: "2.6 The if/else Selection Structure"— Presentation transcript:

1 2.6 The if/else Selection Structure
Only performs an action if the condition is true if/else A different action is performed when condition is true and when condition is false Psuedocode if student’s grade is greater than or equal to 60 print “Passed” else print “Failed” C++ code if ( grade >= 60 ) cout << "Passed"; else cout << "Failed";

2 2.6 The if/else Selection Structure
true false print “Failed” print “Passed” grade >= 60 Ternary conditional operator (?:) Takes three arguments (condition, value if true, value if false) Our pseudocode could be written: cout << ( grade >= 60 ? "Passed" : " Failed " );

3 2.6 The if/else Selection Structure
Nested if/else structures Test for multiple cases by placing if/else selection structures inside if/else selection structures. if student’s grade is greater than or equal to Print “A” else if student’s grade is greater than or equal to Print “B” else if student’s grade is greater than or equal to Print “C” else if student’s grade is greater than or equal to Print “D” else Print “F” Once a condition is met, the rest of the statements are skipped

4 2.6 The if/else Selection Structure
Compound statement: Set of statements within a pair of braces Example: if ( grade >= 60 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n"; } Without the braces, cout << "You must take this course again.\n"; would be automatically executed Block Compound statements with declarations

5 2.7 The while Repetition Structure
Programmer specifies an action to be repeated while some condition remains true Psuedocode while there are more items on my shopping list purchase next item and cross it off my list while loop repeated until condition becomes false. Example int product = 2; while ( product <= 1000 ) product = 2 * product;

6 1. Initialize Variables 2. Execute Loop 3. Output results
1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled repetition 3 #include <iostream> 4 6 using namespace std; 7 8 9 int main() 10 { 11 int total, // sum of grades gradeCounter, // number of grades entered grade, // one grade average; // average of grades 15 16 // initialization phase 17 total = 0; // clear total 18 gradeCounter = 0; // prepare to loop 19 20 // processing phase 21 while ( gradeCounter < 10 ) { // loop 10 times cout << "Enter grade: "; // prompt for input cin >> grade; // input grade total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter 26 } 27 28 // termination phase 29 average = total / 10; // integer division 30 cout << "Class average is " << average << endl; 31 32 return 0; // indicate program ended successfully 33 } 1. Initialize Variables 2. Execute Loop 3. Output results The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.

7 Program Output Enter grade: 98 Enter grade: 76 Enter grade: 71
Class average is 81 Program Output

8 Assignment expression abbreviations
2.11 Assignment Operators Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator Statements of the form variable = variable operator expression; can be rewritten as variable operator= expression; Examples of other assignment operators include: d -= (d = d - 4) e *= (e = e * 5) f /= (f = f / 3) g %= (g = g % 9)

9 2.12 Increment and Decrement Operators
Increment operator (++) can be used instead of c += 1 Decrement operator (--) can be used instead of c -= 1 Preincrement When the operator is used before the variable (++c or ––c) Variable is changed, then the expression it is in is evaluated. Postincrement When the operator is used after the variable (c++ or c--) Expression the variable is in executes, then the variable is changed. If c = 5, then cout << ++c; prints out 6 (c is changed before cout is executed) cout << c++; prints out 5 (cout is executed before the increment. c now has the value of 6)

10 2.13 Essentials of Counter-Controlled Repetition
The declaration int counter = 0; Names counter Declares counter to be an integer Reserves space for counter in memory Sets counter to an initial value of 0

11 2.14 The for Repetition Structure
The general format when using for loops is for ( initialization; LoopContinuationTest; increment ) statement Example: for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; Prints the integers from one to ten REMARK: the test is executed before entering the for body No semicolon after last statement

12 2.14 The for Repetition Structure
For loops can usually be rewritten as while loops: initialization; while ( loopContinuationTest){ statement increment; } Initialization and increment as comma-separated lists for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl; What does this code do?

13 2.15 Examples Using the for Structure
Program to sum the even numbers from 2 to 100 1 // Fig. 2.20: fig02_20.cpp 2 // Summation with for 3 #include <iostream> 4 using namespace std; 7 8 int main() 9 { 10 int sum = 0; 11 12 for ( int number = 2; number <= 100; number += 2 ) sum += number; 14 15 cout << "Sum is " << sum << endl; 16 17 return 0; 18 } Sum is 2550

14 2.16 The switch Multiple-Selection Structure
Useful when variable or expression is tested for multiple values Consists of a series of case labels and an optional default case true false . case a case a action(s) break case b case b action(s) case z case z action(s) default action(s)

15 2.1 Use switch loop to update count
1 // Fig. 2.22: fig02_22.cpp 2 // Counting letter grades 3 #include <iostream> 4 5 using namespace std; 6 7 8 9 int main() 10 { 11 int grade, // one grade aCount = 0, // number of A's bCount = 0, // number of B's cCount = 0, // number of C's dCount = 0, // number of D's fCount = 0; // number of F's 17 18 cout << "Enter the letter grades." << endl << "Enter the EOF character to end input." << endl; 20 21 while ( ( grade = cin.get() ) != EOF ) { 22 switch ( grade ) { // switch nested in while 24 case 'A': // grade was uppercase A case 'a': // or lowercase a aCount; break; // necessary to exit switch 29 case 'B': // grade was uppercase B case 'b': // or lowercase b bCount; break; 34 1. Initialize variables 2. Input data 2.1 Use switch loop to update count Notice how the case statement is used

16 2.1 Use switch loop to update count 3. Print results
case 'C': // grade was uppercase C case 'c': // or lowercase c cCount; break; 39 case 'D': // grade was uppercase D case 'd': // or lowercase d dCount; break; 44 case 'F': // grade was uppercase F case 'f': // or lowercase f fCount; break; 49 case '\n': // ignore newlines, case '\t': // tabs, case ' ': // and spaces in input break; 54 default: // catch all other characters cout << "Incorrect letter grade entered." << " Enter a new grade." << endl; break; // optional } 60 } 61 62 cout << "\n\nTotals for each letter grade are:" << "\nA: " << aCount << "\nB: " << bCount << "\nC: " << cCount << "\nD: " << dCount << "\nF: " << fCount << endl; 68 69 return 0; 70 } 2.1 Use switch loop to update count 3. Print results break causes switch to end and the program continues with the first statement after the switch structure. Notice the default statement.

17 Program Output Enter the letter grades.
Enter the EOF character to end input. a B c C A d f E Incorrect letter grade entered. Enter a new grade. D b Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 Program Output

18 2.18 The break and continue Statements
Causes immediate exit from a while, for, do/while or switch structure Program execution continues with the first statement after the structure Common uses of the break statement: Escape early from a loop Skip the remainder of a switch structure

19 2.18 The break and continue Statements
Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop In while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executed In the for structure, the increment expression is executed, then the loop-continuation test is evaluated

20 ! (logical NOT, logical negation)
2.19 Logical Operators && (logical AND) Returns true if both conditions are true || (logical OR) Returns true if either of its conditions are true ! (logical NOT, logical negation) Reverses the truth/falsity of its condition Returns true when its condition is false Is a unary operator, only takes one condition Logical operators used as conditions in loops Expression Result true && false false true || false true !false true

21 2.20 Confusing Equality (==) and Assignment (=) Operators
These errors are damaging because they do not ordinarily cause syntax errors. Recall that any expression that produces a value can be used in control structures. Nonzero values are true, and zero values are false Example: if ( payCode == 4 ) cout << "You get a bonus!" << endl; Checks the paycode, and if it is 4 then a bonus is awarded If == was replaced with = if ( payCode = 4 ) cout << "You get a bonus!" << endl; Sets paycode to 4 4 is nonzero, so the expression is true and a bonus is awarded, regardless of paycode.

22 2.21 Structured-Programming Summary
All programs can be broken down into Sequence Selection if, if/else, or switch Any selection can be rewritten as an if statement Repetition while, do/while or for Any repetition structure can be rewritten as a while statement


Download ppt "2.6 The if/else Selection Structure"

Similar presentations


Ads by Google