Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued.

Similar presentations


Presentation on theme: "CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued."— Presentation transcript:

1 CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued

2 Chapter 4 Topics Menus Nested if Statements Logical Operators Checking Numeric Ranges Validating User Input More variable Declarations and Scope Variables with the same names Comparing Strings The Conditional Operator The switch

3 Menus A menu is a list of alternative actions from which the user can select –The user makes a decision and the program acts on it –The if/else if statement determines what the decision is from a list of valid decisions Menus can both document the programs functions as well as direct their execution Concept - You can use the if/else if statement to create menu driven programs

4 Program 4-14 // This program displays a menu and asks the user to make a // selection. An if/else if statement determines which item // the user has chosen. #include void main(void) { int Choice, Months; float Charges; cout << "\t\tHealth Club Membership Menu\n\n"; cout << "1. Standard Adult Membership\n"; cout << "2. Child Membership\n"; cout << "3. Senior Citizen Membership\n"; cout << "4. Quit the Program\n\n"; cout << "Enter your choice: "; cin >> Choice; cout.setf(ios::fixed | ios::showpoint); cout.precision(2); if (Choice == 1) { cout << "\nFor how many months? "; cin >> Months; Charges = Months * 40.00; cout << "The total charges are $" << Charges << endl; }

5 Program continues else if (Choice == 2) { cout << "\nFor how many months? "; cin >> Months; Charges = Months * 20.00; cout << "The total charges are $" << Charges << endl; } else if (Choice == 3) { cout << "\nFor how many months? "; cin >> Months; Charges = Months * 30.00; cout << "The total charges are $" << Charges << endl; } else if (Choice != 4) { cout << "The valid choices are 1 through 4. Run the\n"; cout << "program again and select one of those.\n"; } Program Output Health Club Membership Menu 1. Standard Adult Membership 2. Child Membership 3. Senior Citizen Membership 4. Quit the Program Enter your choice: 3 [Enter] For how many months? 6 [Enter] The total charges are $180.00

6 Nested if Statements All the conditions of a nested if must be true for the conditional code to execute. Use proper indentation to help keep track of what else belongs to what if Concept - A nested if statement is an if statement in the conditionally executed code of another if statement

7 if expression end True False Statement or block if expression True False Flow chart for nested if

8 Program 4-15 // This program demonstrates the nested if statement. #include void main(void) { char Employed, RecentGrad; cout << "Answer the following questions\n"; cout << "with either Y for Yes or "; cout << "N for No.\n"; cout << "Are you employed? "; cin >> Employed; cout << "Have you graduated from college "; cout << "in the past two years? "; cin >> RecentGrad; if (Employed == 'Y') { if (RecentGrad == 'Y') { cout << "You qualify for the special "; cout << "interest rate.\n"; } Program Output Answer the following questions with either Y for Yes or N for No. Are you employed? Y Have you graduated from college in the past two years? Y You qualify for the special interest rate.

9 Logical Operators &&andif both sub-expressions are true their connection is true ||orif either sub-expression is true the connection is true !NotReverses the truth of an expression Concept - Logical operators connect two or more relational expressions into one or reverse the logic of an expression

10 Truth Table for Logical Operators And exp 1 True &&exp 1 False Orexp 1 True || exp 1 False exp 2 exp 2 TrueFalse T FFT Notexp True = = False(0) !exp False = = True(1)

11 Program 4-17 /* This program demonstrates the && logical operator.*/ #include void main(void) { char Employed, RecentGrad; cout << "Answer the following questions\n"; cout << "with either Y for Yes or "; cout << "N for No.\n"; cout << "Are you employed? "; cin >> Employed; cout << "Have you graduated from college "; cout << "in the past two years? "; cin >> RecentGrad; if (Employed == 'Y'&& RecentGrad == 'Y') { cout << "You qualify for the special "; cout << "interest rate.\n"; } else { cout << "You must be employed and have \n"; cout << "graduated from college in the\n"; cout << "past two years to qualify.\n"; }

12 Program Output Answer the following questions with either Y for Yes or N for No. Are you employed? Y Have you graduated from college in the past two years? N You must be employed and have graduated from college in the past two years to qualify.

13 Program 4-18 /* This program asks the user for their annual income and the number of years they have been employed at their current job. The || operator is used in a if statement that determines if the income is at least $35,000 or their time on the job is more than 5 years.*/ #include void main(void) { float Income; int Years; cout << "What is your annual income? "; cin >> Income; cout << "How many years have you worked at " << "your current job? "; cin >> Years; if (Income >= 35000 || Years > 5) cout << "You qualify.\n"; else { cout << "You must earn at least $35,000 or have\n"; cout << "been employed for more than 5 years.\n"; } Program Output What is your annual income? 40000 [Enter] How many years have you worked at your current job? 2 [Enter] You qualify. Program Output What is your annual income? 20000 [Enter] How many years have you worked at your current job? 7 [Enter] You qualify.

14 Program 4-19 #include void main(void) { float Income; int Years; cout << "What is your annual income? "; cin >> Income; cout << "How many years have you worked at " << "your current job? "; cin >> Years; //(Income >= 35000 || Years > 5) if (!(Income >= 35000 || Years > 5)) { cout << "You must earn at least $35,000 or have\n"; cout << "been employed for more than 5 years.\n"; } else cout << "You qualify.\n"; }

15 Precedence of Logical Operators ! && ||

16 4.11 Checking Numeric Ranges With Logical Operators Logical operators are effective for determining if a number is in or out of a range.

17 Checking Numeric Ranges Use && to check if values are inside of a range if ( value > = low end && value < = high end) cout << "The value is inside the range"; Use || to check if values are outside of a range if ( value = high end) cout << "The value is outside the range"; Concept - Logical operators are effective for checking if a number is in or out of a range

18 Examples of validation: Numbers are checked to ensure they are within a range of possible values. Values are checked for their “reasonableness”. Items selected from a menu or other set of choices are checked to ensure they are available options. Variables are checked for values that might cause problems, such as division by zero.

19 Validating User Input Range checking - the temperature of liquid water should be between 32 o F and 212 o F Reasonableness checking - there are only 168 hours in a week Acceptable menu selection - is the input one of the menu options Useable inputs - divide by zero Concept - Garbage in equals garbage out. Write programs to filter out bad data

20 Program 4-21A #include void main(void) { cout << "What is your annual income? "; float Income; cin >> Income; cout << "How many years have you worked at " << "your current job? "; int Years; cin >> Years; if (Income >= 35000 || Years >5) cout << "You qualify.\n"; else { cout << "You must earn at least $35,000 or have\n"; cout << "been employed for more than 5 years.\n"; }

21 Program 4-22 // This program demonstrates a variable declared in an inner block. #include void main(void) { cout << "What is your annual income? "; float Income; cin >> Income; if (Income >= 35000) { int Years; cout << "How many years have you worked at your current job? "; cin >> Years; if (Years > 5) cout << "You qualify.\n"; else { cout << "You must have been employed for\n"; cout << "more than 5 years to qualify.\n"; } else { cout << "You must earn at least $35,000 to\n"; cout << "qualify.\n"; }

22 More variable Declarations and Scope Braces { } are used to signify a block of code. –A variable can only be used within the block in which it is declared –This is referred to as local scope or block scope Concept - The scope of a variable is limited to the block of code in which it is declared

23 Variables with the same names If one block of code is nested within another it can declare variables with the same names as those in the outer block –The variable will only exist wile the code in that block is executing –the variables in the outer block won't be useable until the inner block is exited Concept - A variable declared in an inner block can have the same name as a variable declared in an outer block

24 Program 4-23 // This program uses two variables with the name Number. #include void main(void) { int Number; cout << "Enter a number greater than 0: "; cin >> Number; if (Number > 0) { int Number; cout << "Now enter another number: "; cin >> Number; cout << "The second number you entered was "; cout << Number << endl; } cout << "Your first number was " << Number << endl; } Program Output Enter a number greater than 0: 2 [Enter] Now enter another number: 7[Enter] The second number you entered was 7 Your first number was 2

25 Comparing Strings The strcmp function is used to compare character strings strcmp(string1, string2) returns 1 if string1 is alphabetically higher returns -1 if string2 alphabetically higher returns 0 if both strings are identical #include is required to use strcmp Concept - Character strings can not be compared using relational operators.

26 Sorting Strings If (strcmp(string1,string2)) < 0) cout <<string1<<"\n" <<string2; else cout << string2<<"\n" <<string1; Concept - The strcmp function can be used to alphabetically sort character strings

27 The Conditional Operator The conditional operator is a ternary operator expression1 ? expresson2 : espression3 if (expression1) expression2; else expression3; Concept - The conditional operator can be used to create short expressions that work like if/else statements

28 The switch The switch statement test the value of an integer expression and then uses the value to determine which block of code to branch to switch (integer expression) { case result1: constant expression: one or more statements; break; case result2: constant expression: one or more statements; break; default: statement; (optional) } Concept - The switch statement lets the value of a variable or expression determine where the program will branch to

29 Switch Flow Chart if Case Statement or block end True False Statement or block if Case True False if break True False if break Default False True

30 The switch statement The expressions in case statements must be unique The default statement is optional A break is not needed after the last statement The switch statement is a natural for building menus

31 Program 4-31 /* The switch statement in this program tells the user something he or she already knows: what they just entered! */ #include void main(void) { char Choice; cout << "Enter A, B, or C: "; cin >> Choice; switch (Choice) { case 'A': cout << "You entered A.\n"; break; case 'B': cout << "You entered B.\n"; break; case 'C': cout << "You entered C.\n"; break; default: cout << "You did not enter A, B, or C!\n"; } Program Output Enter A, B, or C: B [Enter] You entered B. Program Output Enter a A, B, or C: F [Enter] You did not enter A, B, or C!

32 Program 4-32 /* The switch statement in this program tells the user something he or she already knows: what they just entered! */ #include void main(void) { char Choice; cout << "Enter A, B, or C: "; cin >> Choice; switch (Choice) { case 'A': cout << "You entered A.\n"; case 'B': cout << "You entered B.\n"; case 'C': cout << "You entered C.\n"; default: cout << "You did not enter A, B, or C!\n"; } Program Output Enter a A, B, or C: A [Enter] You entered A. You entered B. You entered C. You did not enter A, B, or C! Program Output Enter a A, B, or C: C [Enter] You entered C. You did not enter A, B, or C!

33 Program 4-33 /* This program is carefully constructed to use the "fallthrough" feature of the switch statement. */ #include void main(void) { int ModelNum; cout << "Our TVs come in three models:\n"; cout << "The 100, 200, and 300. Which do you want? "; cin >> ModelNum; cout << "That model has the following features:\n"; switch (ModelNum) { case 300:cout << "\tPicture-in- a-picture.\n"; case 200:cout << "\tStereo sound.\n"; case 100:cout << "\tRemote control.\n"; break; default:cout << "You can only choose the 100,"; cout << "200, or 300.\n"; }

34 Program Output with Example Input Our TVs come in three models: The 100, 200, and 300. Which do you want? 100 [Enter] That model has the following features: Remote control. Program Output with Example Input Our TVs come in three models: The 100, 200, and 300. Which do you want? 200 [Enter] That model has the following features: Stereo sound. Remote control.

35 Program 4-34 /*The switch statement in this program uses the "fallthrough“ feature to catch both upper and lowercase letters entered by the user. */ #include void main(void) { char FeedGrade; cout << "Our dog food is available in three grades:\n"; cout << "A, B, and C. Which do you want pricing for? "; cin >> FeedGrade; switch(FeedGrade) { case 'a': case 'A':cout << "30 cents per pound.\n"; break; case 'b': case 'B':cout << "20 cents per pound.\n"; break; case 'c': case 'C':cout << "15 cents per pound.\n"; break; default:cout << "That is an invalid choice.\n"; }


Download ppt "CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued."

Similar presentations


Ads by Google