Lecture 8: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 4: Making Decisions.
Advertisements

Chapter 4. Making Decisions
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
1 9/25/06CS150 Introduction to Computer Science 1 Nested Ifs, Logical Operators, exit() Page 194.
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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
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.
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Computer Science 1620 Selection Structures. Write a program that accepts the speed of a vehicle, and determines whether that person is speeding assume.
Starting Out with Java: From Control Structures through Objects
CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 4: Control Structures I (Selection)
Chapter 4 Selection Structures: Making Decisions.
1 CS 1430: Programming in C++. 2 Literal Values Literal values of int Literal values of float
Basic Of Computer Science
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Lecture 6: Expressions and Interactivity (Part II) Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
CONTROLLING PROGRAM FLOW
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.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
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.
Copyright 2003 Scott/Jones Publishing Making Decisions.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Selection Structures: if and switch Statements. 2 Selection Statements –In this chapter we study statements that allow alternatives to straight sequential.
Chapter Making Decisions 4. Relational Operators 4.1.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Starting Out with C++: From Control Structures through Objects
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Lecture 14: Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
CS102 Introduction to Computer Programming Chapter 5 Looping.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
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.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
C++ Programming: CS102 LOOP. Not everything that can be counted counts, and not every thing that counts can be counted. −Albert Einstein Who can control.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
Chapter 4. Making Decisions
Chapter 3 Selection Statements
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Chapter 5. Looping.
Chapter 4: Making Decisions.
Alternate Version of STARTING OUT WITH C++ 4th Edition
Chapter 5. Looping.
Functions.
Chapter 3:Decision Structures
Presentation transcript:

Lecture 8: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220

Nested if statements To test more than one condition, an if statement can be nested inside another if statement Proper Indentation and alignment makes it easier to read if(condition) { statement; if(condition) { statement; { }

// This program demonstrates the nested if statement. #include using namespace std; int main() { char employed, // Currently employed, Y or N recentGrad; // Recent graduate, Y or N // Is the user employed and a recent graduate? 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; // Determine the user's loan qualifications. if (employed == 'Y') { if (recentGrad == 'Y') //Nested if { cout << "You qualify for the special "; cout << "interest rate.\n"; } return 0; }

// This program demonstrates the nested if statement. #include using namespace std; int main() { char employed, // Currently employed, Y or N recentGrad; // Recent graduate, Y or N // Is the user employed and a recent graduate? 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; // Determine the user's loan qualifications. if (employed == 'Y') { if (recentGrad == 'Y') // Nested if { cout << "You qualify for the special "; cout << "interest rate.\n"; } else // Not a recent grad, but employed { cout << "You must have graduated from "; cout << "college in the past two\n"; cout << "years to qualify.\n"; } else // Not employed { cout << "You must be employed to qualify.\n"; } return 0; }

Testing a series of conditions You can nest if/else statements as well to test a series of conditions See example, pg 189 In the Spotlight

// This program uses nested if/else statements to assign a // letter grade (A, B, C, D, or F) to a numeric test score. #include using namespace std; int main() { int testScore; // To hold a numeric test score char grade; // To hold a letter grade // Get the numeric test score. cout << "Enter your numeric test score and I will\n"; cout << "tell you the letter grade you earned: "; cin >> testScore; // Determine the letter grade. if (testScore < 60) { cout << "Your grade is F.\n"; } else { if (testScore < 70) { cout << "Your grade is D.\n"; } else { if (testScore < 80) { cout << "Your grade is C.\n"; } else { if (testScore < 90) { cout << "Your grade is B.\n"; } else { cout << "Your grade is A.\n"; } return 0; }

if/else if if/else if also tests a series of conditions and is easier to use than if/else nesting if(condition 1) { statements; } else if(condition 2) { statements; } else { statements; }

// This program uses an if/else if statement to assign a // letter grade (A, B, C, D, or F) to a numeric test score. #include using namespace std; int main() { int testScore; // To hold a numeric test score char grade; // To hold a letter grade // Get the numeric test score. cout << "Enter your numeric test score and I will\n"; cout << "tell you the letter grade you earned: "; cin >> testScore; // Determine the letter grade. if (testScore < 60) cout << "Your grade is F.\n"; else if (testScore < 70) cout << "Your grade is D.\n"; else if (testScore < 80) cout << "Your grade is C.\n"; else if (testScore < 90) cout << "Your grade is B.\n"; else cout << "Your grade is A.\n"; return 0; }

Using the Trailing else to catch errors // This program uses an if/else if statement to assign a // letter grade (A, B, C, D, or F) to a numeric test score. #include using namespace std; int main() { int testScore; // To hold a numeric test score char grade; // To hold a letter grade // Get the numeric test score. cout << "Enter your numeric test score and I will\n"; cout << "tell you the letter grade you earned: "; cin >> testScore; // Determine the letter grade. if (testScore < 60) cout << "Your grade is F.\n"; else if (testScore < 70) cout << "Your grade is D.\n"; else if (testScore < 80) cout << "Your grade is C.\n"; else if (testScore < 90) cout << "Your grade is B.\n"; else if (testScore <= 100) cout << "Your grade is A.\n"; else cout << "We do not give scores higher than 100.\n"; return 0; }

Menus You can use nested if/else statements or the if/else if statement to create menu-driven programs This allows the user to determine the course of action by selecting it from a list of actions or choices

// 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 using namespace std; int main() { int choice; // Menu choice int months; // Number of months double charges; // Monthly charges // Constants for membership rates const double ADULT = 40.0; const double SENIOR = 30.0; const double CHILD = 20.0; // Display the menu and get a choice. 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; // Set the numeric ouput formatting. cout << fixed << showpoint << setprecision(2); // Respond to the user's menu selection. if (choice == 1) { cout << "For how many months? "; cin >> months; charges = months * ADULT; cout << "The total charges are $" << charges << endl; } else if (choice == 2) { cout << "For how many months? "; cin >> months; charges = months * CHILD; cout << "The total charges are $" << charges << endl; } else if (choice == 3) { cout << "For how many months? "; cin >> months; charges = months * SENIOR; cout << "The total charges are $" << charges << endl; } else if (choice == 4) { cout << "Program ending.\n"; } else { cout << "The valid choices are 1 through 4. Run the\n"; cout << "program again and select one of those.\n"; } return 0; }

Logical Operators Logical Operators connect two or more relational expressions into one or reverse the logic of an expression

// This program demonstrates the && logical operator. #include using namespace std; int main() { char employed, // Currently employed, Y or N recentGrad; // Recent graduate, Y or N // Is the user employed and a recent graduate? 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; // Determine the user's loan qualifications. 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"; } return 0; }

// This program asks the user for annual income and // the number of years of employment at the current // job. The || operator is used in a if statement that // determines if the income is at least $35,000 or the time // on the job is more than 5 years. #include using namespace std; int main() { double income; // Annual income int years; // Years at the current job // Get the annual income cout << "What is your annual income? "; cin >> income; // Get the number of years at the current job. cout << "How many years have you worked at " << "your current job? "; cin >> years; // Determine the user's loan qualifications. 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"; } return 0; }

// This program asks the user for their annual income and // the number years they have been employed at their current // job. The ! operator reverses the logic of the expression // in the if/else statement. #include using namespace std; int main() { double income; // Annual income int years; // Years at the current job // Get the annual income cout << "What is your annual income? "; cin >> income; // Get the number of years at the current job. cout << "How many years have you worked at " << "your current job? "; cin >> years; // Determine the user's loan qualifications. 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"; return 0; }

Operator precedence ! && || To avoid problems, enclose expressions in parentheses !(x > 2) v.s. !x > 2

Checking numeric ranges with logical operators Logical operators are effective for determining whether a number is in or out of a range if ( x >= 20 && x <= 40) cout << x << “ is in the acceptable range. \n”

Validating User Input As long as the user of a program enters bad input, the program will produce bad output Programs should be written to filter out bad input. Examples Number ranges Is it reasonable or does it make sense? Is the item part of the menu? Division by zero!

// This program uses an if/else if statement to assign a // letter grade (A, B, C, D, or F) to a numeric test score. #include using namespace std; int main() { int testScore; // To hold a numeric test score char grade; // To hold a letter grade // Get the numeric test score. cout << "Enter your numeric test score and I will\n"; cout << "tell you the letter grade you earned: "; cin >> testScore; if (testScore 100) //Input validation { // An invalid score was entered. cout << testScore << " is an invalid score.\n"; cout << "Run the program again and enter a value\n"; cout << "in the range of 0 to 100.\n"; } else { // Determine the letter grade. if (testScore < 60) cout << "Your grade is F.\n"; else if (testScore < 70) cout << "Your grade is D.\n"; else if (testScore < 80) cout << "Your grade is C.\n"; else if (testScore < 90) cout << "Your grade is B.\n"; else if (testScore <= 100) cout << "Your grade is A.\n"; } return 0; }

The conditional operator You can use the conditional operator to create short expressions that work like if/else statements Remember, all expressions in C++ have a value, including the conditional expression expression ? expression : expression; x < 0 ? Y = 10 : z = 20; a = x < 0 ? Y = 10 : z = 20;

// This program calculates a consultant's charges at $50 // per hour, for a minimum of 5 hours. The ?: operator // adjusts hours to 5 if less than 5 hours were worked. #include using namespace std; int main() { const double PAY_RATE = 50.0; double hours, charges; cout << "How many hours were worked? "; cin >> hours; hours = hours < 5 ? 5 : hours; //conditional operator charges = PAY_RATE * hours; cout << fixed << showpoint << setprecision(2); cout << "The charges are $" << charges << endl; return 0; }