C Programming From Problem Analysis to Program Design

C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures

Objectives In this chapter, you will: • Learn about control structures • Examine relational and logical operators • Explore how to form and evaluate logical (Boolean) expressions • Discover how to use the selection control structures if, if. . . else, and switch in a program C++ Programming: From Problem Analysis to Program Design, Fourth Edition 2

Logical expression Example: int a=10; cout << a; cout<< (a==1) ; cout<< (a>1); cout <<(a=5); a = (a != 5); Prints 10 Prints 0. Is 10==1 ? => False =>0 Prints 1. Is 10>1 ? => True => 1 Prints 5. This is not a logical expression, but it is a assignment expression. a=0

Logical operator complements Another way to complement an expression, put the Not operator (!) infront of it. Example: Complement of n==0 is !(n==0)

When to use complement? Example 1: Solution: Complement the condition. !(n==0) or n != 0 In order to convert the flowchart to C code, this part must be “Yes (True)”

Relational Operators and Simple Data Types • You can use the relational operators with all three simple data types: − 8 < 15 evaluates to true − 6 != 6 evaluates to false − 2. 5 > 5. 8 evaluates to false − 5. 9 <= 7. 5 evaluates to true C++ Programming: From Problem Analysis to Program Design, Fourth Edition 7

Comparing Floating-Point Numbers for Equality • Comparison of floating-point numbers for equality may not behave as you would expect − Example: • 1. 0 == 3. 0/7. 0 + 2. 0/7. 0 evaluates to false • Why? 3. 0/7. 0 + 2. 0/7. 0 = 0. 9999999989 • Solution: use a tolerance value − Example: fabs(x – y) < 0. 000001 C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8

Comparing Characters C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9

Relational Operators and the string Type • Relational operators can be applied to strings • Strings are compared character by character, starting with the first character • Comparison continues until either a mismatch is found or all characters are found equal • If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string − The shorter string is less than the larger string C++ Programming: From Problem Analysis to Program Design, Fourth Edition 10

Relational Operators and the string Type (continued) string str 1 = "Hello“, str 2 = "Hi“, str 3 = "Air“, str 4 = "Bill“, str 4 = "Big"; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 11

Relational Operators and the string Type (continued) string str 1 = "Hello“, str 2 = "Hi“, str 3 = "Air“, str 4 = "Bill“, str 4 = "Big"; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12

Relational Operators and the string Type (continued) string str 1 = "Hello“, str 2 = "Hi“, str 3 = "Air“, str 4 = "Bill“, str 4 = "Big"; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 13

Order of Precedence (continued) C++ Programming: From Problem Analysis to Program Design, Fourth Edition 14

Two-Way Selection • Two-way selection takes the form: • If expression is true, statement 1 is executed; otherwise, statement 2 is executed − statement 1 and statement 2 are any C++ statements • else is a reserved word C++ Programming: From Problem Analysis to Program Design, Fourth Edition 15

Making decisions • Sometimes your programs need to make logical choices. • Example: IF score is higher than 50 THEN grade is PASS ELSE grade is FAIL • In C, this corresponds to if statement with three parts: if (score > 50) //part 1 { grade = PASS; //part 2 } else { grade = FAIL; //part 3 }

if statement • Part 1 : the condition - an expression that is evaluated to TRUE or FALSE. (score > 50) if { grade = PASS; } else { grade = FAIL; }

if statement • Part 2 : the TRUE-PART - a block of statements that are executed if the condition evaluates to TRUE if (score > 50) { grade = PASS; } else { grade = FAIL; }

if statement • Part 3 : the FALSE-PART - a block of statements that are executed if the condition evaluates to FALSE if (score > 50) { grade = PASS; } else { grade } = FAIL; if the condition evaluates to FALSE, the TRUE-PART is skipped.

Two-Way Selection (continued) C++ Programming: From Problem Analysis to Program Design, Fourth Edition 20

Two-Way Selection (continued) C++ Programming: From Problem Analysis to Program Design, Fourth Edition 21

One-Way Selection • Sometimes there is no FALSE-PART: if ( attendance < 0. 8 ) { exam_grade = FAIL; }


One-Way Selection (continued) C++ Programming: From Problem Analysis to Program Design, Fourth Edition 24

Compound (Block of) Statement • Three forms of if statements are shown at the next table. • The condition is always in parentheses • All TRUE-PARTS and all FALSEPARTS are a single statement or a block of statements (also called compound statement) if(condition) statement; if (condition) { statement; } else { statement; }

Compound (Block of) Statement (continued) • Compound statement (block of statements): • A compound statement is a single statement C++ Programming: From Problem Analysis to Program Design, Fourth Edition 26

Compound (Block of) Statement (continued) • If the TRUE-PART (or FALSE-PART) consists of only one statement, then the curly braces may be omitted. • Example: these two statements are equivalent: if (score > 50) { grade = PASS; } else { grade = FAIL; } if (score > 50) grade = PASS; else grade = FAIL;

Compound (Block of) Statement (continued) if (age > { cout << } else { cout << } 18) "Eligible to vote. " << endl; "No longer a minor. " << endl; "Not eligible to vote. " << endl; "Still a minor. " << endl; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28

Compound (Block of) Statement (continued) • A compound statement is a one or more statements that are grouped into a single block. It is enclosed with the bracket symbols, {}. • Example: if (value>0) cout << value ; value = value * 2; a single statement if (value> 10) { value = 10; cout << value; } a compound statement

Multiple Selections: Nested if • Nesting: one control statement in another • An else is associated with the most recent if that has not been paired with an else C++ Programming: From Problem Analysis to Program Design, Fourth Edition 30


Multiple Selections: Nested if (continued) C++ Programming: From Problem Analysis to Program Design, Fourth Edition 32

Comparing if…else Statements with a Series of if Statements C++ Programming: From Problem Analysis to Program Design, Fourth Edition 33

Conditional Operator (? : ) • Conditional operator (? : ) takes three arguments − Ternary operator • Syntax for using the conditional operator: expression 1 ? expression 2 : expression 3 • If expression 1 is true, the result of the conditional expression is expression 2 − Otherwise, the result is expression 3 C++ Programming: From Problem Analysis to Program Design, Fourth Edition 34

Simplifying if statements • Conditional Expressions:

Simplifying if statements • Conditional Expressions: If the condition is True, take the value 1 Syntax: condition ? value 1 : value 2 Example: p = (q<5) ? If the condition is False, take the value 2 q + 1 : 5; This statement means if (p<5) p = q + 1; else p = 5;

switch statement • If there are many nested if/else statements, you may be able to replace them with a switch statement: if (letter_grade == 'A') cout << "Excellent!"; else if (letter_grade == 'B') cout << "Very good!"; else if (letter_grade == 'C') cout << "Good"; else if (letter_grade == 'D') cout << "Adequate"; else switch (letter_grade) { case 'A‘ : cout << "Excellent!"; break; case 'B' : cout << "Very good!"; break; case 'C' : cout << "Good"; break; cout<< "Fail"; case 'D' : cout << "Adequate"; break; default } : cout << "Fail"; break;

switch statement switch (expression) { case value 1: statements_1; break; case value 2 : statements_2; break; . . . default : statements; break; } How the switch statement works? 1. Check the value of expression. 2. Is it equal to value 1? – If yes, execute the statements_1 and break out of the switch. – If no, is it equal to value 2? etc. 3. If it is not equal to any values of the above, execute the default statements and then break out of the switch.

switch statement Example 1: int value = 1; evaluates to 1 it is equal to this case-value (i. e. 1==1). So, execute the statements of the case 1. switch (value) { case 1: cout << “One”; break; Prints One break out of the switch case 2: cout << “Two”; break; default : cout << “Neither One nor Two”; break; } Output: One

switch statement Example 2: it is not equal to this case-value (i. e. 2!=1). So, skip the statements of case 1 and move to the next case. it is equal to this case-value (i. e. 2==2). So, execute the statements of the ‘case 2‘. int value = 1; this expression evaluates to 2 switch (value + 1) { case 1: cout << “One”; break; case 2: cout << “Two”; break; Prints Two break out of the switch default : cout << “Neither One nor Two”; break; } Output: Two

switch statement Example 3: The switch expression (i. e. 5) is not equal to both cases (i. e 5!=1 and 5!=2). So, their statements are skipped. When the ‘default case’ is reached, its statements are always executed. int value = 5; evaluates to 5 switch (value) { case 1: cout << “One”; break; case 2: cout << “Two”; break; default : cout << “Neither One nor Two”; break; Prints Neither } break out of the switch Output: Neither One nor Two

switch statement int value = 1; it is equal to this case-value (i. e. 1==1). So, execute the statements of the case 1. evaluates to 1 switch (value) { case 1: cout << “Onen”; case 2: cout << “Two”; break; Prints One No break statement here. So, no break out and move to the next line. Prints Two break out of the switch What if the break statement is not written? default : cout << “Neither One nor Two”; break; } Output: One Two

switch statement • The switch expression must be an int or a char. • The following examples would be an error int main() { float point=4. 0; Error! The switch int mark; expression cannot be a float value switch (point) { case 4 : mark = 100; break; int main() { char name[]="Ali"; int mark; Error! The switch expression cannot switch (name) be a string value { case "Ali" : mark=95; break; case 3. 7 : mark = 80; break; case "Aminah": mark=90; break; default : mark = 0; break; } } : mark=50; break;

switch statement • The case-value must be a constant (literal, memory or defined constant) • The following example would be an error int main() { #. . . const int const 2=2; int var 3 = 3; int value; switch (value) { case 0 a literal is OK case DEFINE a defined constant is OK case const 2 a memory constant is OK Error! case-value cannot be a variable case var 3 } } : cout <<"Four"; break; : cout <<"One"; break; : cout <<"Two"; break; : cout <<"Three"; break;

Translating flowchart to C code Pattern 1 This must be True if (condition) { statement; }

Translating flowchart to C code Pattern 2 if (condition) { statement_1; } else { statement_2; }

Translating flowchart to C code Pattern 3 if (condition_1) { statement_1; } else if (condition_2) { statement_2; } else if (condition_n) { statement_n; } else { statement_m; }

Translating flowchart to C code Example 3: Identifying the grade of a score if (score > 90) { grade = 'A'; } else if (score > 75) { grade = 'B'; } else if (score > 60) { grade = 'C'; } else if (score > 50) { grade = 'D'; } else { grade = 'F'; }


switch Structures • switch structure: alternate to if-else • switch (integral) expression is evaluated first • Value of the expression determines which corresponding action is taken • Expression is sometimes called the selector C++ Programming: From Problem Analysis to Program Design, Fourth Edition 50

switch Structures (continued) • One or more statements may follow a case label • Braces are not needed to turn multiple statements into a single compound statement • The break statement may or may not appear after each statement • switch, case, break, and default are reserved words C++ Programming: From Problem Analysis to Program Design, Fourth Edition 51

Translating flowchart to C code Pattern 4 • The conditions must be in this form: expression == value switch (expr) { case val_1 : } statement_1; break; case val_2 : statement_2; break; case val_n : statement_n; break; default: statement_m; break;

Translating flowchart to C code Example 4: Printing the description of a grade. switch (grade) { case 'A‘ : printf("Excellent!"); break; case 'B' : printf("Very good!"); break; case 'C' : printf("Good"); break; case 'D' : printf("Adequate"); break; default } : printf("Fail"); break;


Summary • Control structures alter normal control flow • Most common control structures are selection and repetition • Relational operators: ==, <, <=, >, >=, != • Logical expressions evaluate to 1 (true) or 0 (false) • Logical operators: ! (not), && (and), || (or) C++ Programming: From Problem Analysis to Program Design, Fourth Edition 55

Summary (continued) • Two selection structures: one-way selection and two-way selection • The expression in an if or if. . . else structure is usually a logical expression • No stand-alone else statement in C++ − Every else has a related if • A sequence of statements enclosed between braces, { and }, is called a compound statement or block of statements C++ Programming: From Problem Analysis to Program Design, Fourth Edition 56

Summary (continued) • Using assignment in place of the equality operator creates a semantic error • switch structure handles multiway selection • break statement ends switch statement C++ Programming: From Problem Analysis to Program Design, Fourth Edition 57
- Slides: 56