Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Week 7
Making Decisions
Source from Tony Gaddis, Barret Krupnow, Starting out with C++, 5th edition update. 2007. Pearson Addison-Wesley
Selection structure Selection will be chosen based on conditions In C, there are 3 ways for selection structure:
1. Selection using if & else
if, expanding if, if/else, if/else if, trailing else, nested if
2. Selection using conditional operators 3. Selection using switch, case & break
4.1
Relational Operators & Logical Operators
Relational Operators
Logical Operators Used to create relational expressions from other relational expressions Operators, meaning, and explanation:
&& || AND OR New relational expression is true if both expressions are true New relational expression is true if either expression is true Reverses the value of an expression true expression becomes false, and false becomes true
NOT
Logical data
Also called Boolean In C, there is no True or False Value. A Zero value is treated as False A Non-Zero value is treated as True
4.2
The if Statement
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." "If it is cold outside, wear a coat."
If the expression is true, then statement is executed. If the expression is false, then statement is skipped.
if statement - example
if statement notes
Do not place ; after (expression) Place statement; on a separate line after (expression), indented:
if (score > 90) grade = 'A';
Be careful testing float and double for equality 0 is false; any other value is true
Flowchart if
Exercise Week 7_1 Refer to Lab 7, Exe 2 No. 1 (i) in pg. 60. Explain and draw the flowchart
4.3
Flags
Flags Variable that signals a condition Usually implemented as a bool variable As with other variables in functions, must be assigned an initial value before it is used
4.4
Expanding the if Statement
4.5
The if/else Statement
Provides two possible paths of execution Performs one statement or block if the expression is true, otherwise performs another statement or block.
If the expression is true, then statement1 is executed and statement2 is skipped. If the expression is false, then statement1 is skipped and statement2 is executed.
if statement example condition Part 1: the condition an expression that is evaluated to TRUE or FALSE
if statement TRUE Part 2: the TRUE-part a block of statements that are executed if the condition evaluates to TRUE
else statement FALSE Part 3: the FALSE-part a block of statements that are executed if the condition evaluates to FALSE
Flowchart if/else
Flowchart 2 - if/else
Example: if two numbers (p and q) are equivalent, reset them to zero, otherwise, exchange or swap their value and then print the new values.
Exercise Week 7_4 Refer back to Lab 7, Exe 2, No. 1, pg. 60. Solve the problem in (ii) and (iii) pg.61
4.6
The if/else if Statement
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
if/else if format
if (expression) statement1; // or block else if (expression) statement2; // or block . . // other else ifs . else if (expression) statementn; // or block
(Program Continues )
Exercise Week 7_5 Refer to Lab 7, Exe 3, No. 1 in pg. 62. Draw a flowchart for Program 7.3 Refer to Lab 7, Exe 3, No. 2 in pg. 62-63. Draw a flowchart for Program 7.4
4.7
Using a Trailing else
Used with if/else if statement when none of the expressions are true
Provides default statement/action Used to catch invalid values, other exceptional situations
4.8
Menus
Menus
Menu-driven program: program execution controlled by user selecting from a list of actions Menu: list of choices on the screen Menus can be implemented using if/else if statements
Display list of numbered or lettered choices for actions Prompt user to make selection Test user selection in expression
if a match, then execute code for action if not, then go on to next expression
Exercise Week 7_6 Refer to Lab 7, Exe. 4, No. 1, Program 7.5. in pg. 63. Use if / else.if to select the menu Use trailing else to print We dont have any Jump to switch slide #93
4.9
Nested if Statements
Nested if Statements An if statement that is part of the if or else part of another if statement Can be used to evaluate more than one condition:
if (score < 100) { if (score > 90) grade = 'A'; } or,
condition1 condition2
condition3 TRUE-part,
Nested if Statements Problem-solving example Write a program to calculate and display an area of a rectangle. Size of each side is given by a user from a keyboard. Your program must ensure that the size of each side is not zero or negative. If side is zero, display a warning message to the user and turn the area into zero. If the side given is negative, only take the magnitude.
3.1.3 if negative width, then 3.1.3.1 width = magnitude width 3.1.4 end_if 3.1.5 area = length * width 3.2 end_else 4. print area
2-tier nested if
Nested if Statements multiple tiers Defense Ministry is to list names of male staffs whose age is between 20-26 and not yet married
if (gender == M) if (marital_status == S) if (age <= 26) if (age >= 20) printf (%s\n, name);
Notes on coding nested ifs An else matches the nearest if that does not have an else:
if (score < 100) if (score > 90) grade = 'A'; else ...// goes with second if, // not first one
Exercise Week 7_7 Write nested if statements that perform the following test: If amount1 is greater than 10 and amount2 is less than 100, display the greater of the two.
4.10
Logical Operators
Logical operators Used to create relational expressions from other relational expressions Operators, meaning, and explanation:
&& || AND OR New relational expression is true if both expressions are true New relational expression is true if either expression is true Reverses the value of an expression true expression becomes false, and false becomes true
NOT
4.11
Checking Numeric Ranges with Logical Operators
4.12
Validating User Input
Validating User Input Input validation: inspecting input data to determine whether it is acceptable Bad output will be produced from bad input Can perform various tests:
Range Reasonableness Valid menu choice Divide by zero
4.13
More About Variable Definitions and Scope
More About Variable Definitions and Scope Scope of a variable is the block in which it is defined, from the point of definition to the end of the block Usually defined at beginning of function May be defined close to first use
Variables defined inside { } have local or block scope When inside a block within another block, can define variables with the same name as in the outer block.
When in inner block, outer definition is not available Not a good idea
Exercise Week 7_8 What will the following program display if user enter test1 40 and test2 30?
int main () { int test1; printf ("Enter Test 1 score: "); scanf ("%d", &test1); int test2; printf ("Enter Test 2 score: "); scanf ("%d", &test2); int sum=test1+test2; printf ("Sum: %d \n", sum); if (sum>60){ int bonus=10; test1+=bonus; test2+=bonus; int sum=test1+test2; printf ("Test 1 with bonus: %d \n", test1); printf ("Test 2 with bonus: %d \n", test2); printf ("Sum with bonus: %d \n", sum); } printf ("Test 1 : %d \n", test1); printf ("Test 2 : %d \n", test2); printf ("Sum: %d \n", sum); getch(); return 0; }
(cont. next)
4.14
Comparing Strings
Comparing Strings You cannot use relational operators with C-strings Must use the strcmp function to compare C-strings strcmp compares the ASCII codes of the characters in the C-strings. Comparison is character-by-character
strcmp(The, the)
will return 32 which is the numeric difference between ASCII T & ASCII t.
Exercise Week 7_9 Refer back to Lab 7, Exe. 4, Program 7.5 in pg. 63. Change the program that you wrote in Exercise Week 7_6 :
Change variable choice to variable iceCream[20] Instead of using menu, use gets so the user can enter the flavor and use strcmp to if / elseif statement.
4.15
The Conditional Operator
Can use to create short if/else statements Format: expr ? expr : expr;
x<0 ? y=10 : z=20;
(x<0)?(y=10):(z=20);
a=x>100?0:1;
printf ("How many hours were worked? "); scanf ("%lf", &hours); hours = hours < 5 ? 5 : hours; //conditional operator charges = PAY_RATE * hours; printf ("The charges are $%.2lf", charges); getch(); return 0;
}
4.16
The switch Statement
The switch Statement Used to select among statements from several alternatives In some cases, can be used instead of if/else if statements
1) expression must be an integer 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
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 following expi and continues to the end of the switch
4) If no matching value is found, the program branches to the statement after default:
break statement
Flowchart - switch
Using switch with a menu switch statement is a natural choice for menu-driven program:
display the menu then, get the user's menu selection use user input as expression in switch statement use menu choices as expr in case statements
4.17
Testing for File Open Errors
Exercise Week 7_12 Refer to Lab 6, Exe.2. Program 6.3 in pg. 58. Modify the program to detect if the open files operation failed.
Thank You
Q&A