CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 4: Making Decisions.
Chapter 4. Making Decisions
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
C++ Programming, Namiq Sultan1 Chapter 4 Making Decisions Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 4 Making Decisions.
Chapter 4 Making Decisions
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 4 Making.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 4 Selection Structures: Making Decisions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CS102 Introduction to Computer Programming Chapter 4 Making Decisions.
Chapter 4: Making Decisions. Resource: Starting Out with C++, Third Edition, Tony Gaddis 4.1 Relational Operators Relational operators allow you to compare.
Starting Out with C++: From Control Structures through Objects 7 th edition By Tony Gaddis Source Code Chapter 4.
Flow of Control Part 1: Selection
CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Chapter 3:Decision Structures.  3.1 The if Statement  3.2 The if-else Statement  3.3 The if-else-if Statement  3.4 Nested if Statements  3.5 Logical.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Lecture 8: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions Starting Out with C++ Early Objects Seventh Edition.
Copyright 2003 Scott/Jones Publishing Making Decisions.
+ Chapter 4: Making Decisions Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated.
PEG200/Saidatul Rahah 1.  Selection Criteria › if..else statement › relational operators › logical operators  The if-then-else Statement  Nested if.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
C++ Programming Lecture 7 Control Structure I (Selection) – Part II The Hashemite University Computer Engineering Department.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
1 CS161 Introduction to Computer Science Topic #8.
CPS120: Introduction to Computer Science Decision Making in Programs.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
A First Book of C++ Chapter 4 Selection.
Chapter 4. Making Decisions
Chapter 4: Making Decisions.
Chapter 2.1 Control Structures (Selection)
Chapter 5. Looping.
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Alternate Version of STARTING OUT WITH C++ 4th Edition
Chapter 5. Looping.
Chapter 3:Decision Structures
Chapter 7 Conditional Statements
Topics 4.1 Relational Operators 4.2 The if Statement
Chapter 3: Selection Structures: Making Decisions
Chapter 3: Selection Structures: Making Decisions
Selection Control Structure
Presentation transcript:

CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued

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

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

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; }

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

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

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

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.

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

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)

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"; }

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.

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 >= || 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? [Enter] How many years have you worked at your current job? 2 [Enter] You qualify. Program Output What is your annual income? [Enter] How many years have you worked at your current job? 7 [Enter] You qualify.

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 >= || Years > 5) if (!(Income >= || 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"; }

Precedence of Logical Operators ! && ||

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

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

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.

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

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 >= || 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 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"; }

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

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

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

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.

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

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

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

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

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

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!

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!

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"; }

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.

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"; }