Chapter 4 Selection Structures: Making Decisions.

Slides:



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

1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
C++ Programming, Namiq Sultan1 Chapter 4 Making Decisions Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
Chapter 4 Making Decisions
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Computer Science Selection Structures.
CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
CPS120: Introduction to Computer Science Decision Making in Programs.
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.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CPS120: Introduction to Computer Science Decision Making in Programs.
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.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
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 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CHAPTER#3 PART1 STRUCTURED PROGRAM DEVELOPMENT IN C++ 2 nd semester King Saud University College of Applied studies and Community Service Csc.
CSCI N201: Programming Concepts Copyright ©2005  Department of Computer & Information Science Working with Selection Structures.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.
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.
Chapter#3 Part1 Structured Program Development in C++
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Chapter 3 Decisions Three control structures Algorithms Pseudocode Flowcharts If…then …else Nested if statements Code blocks { } multi statement blocks.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Loop. 3.1Introduction to Repetition Structures Loop – a block of code that, under certain conditions will be executed repeatedly. Do Prompt for and input.
Chapter 3 Control Statements
REPETITION CONTROL STRUCTURE
Decisions Chapter 4.
Chapter 4: Making Decisions.
Engineering Problem Solving with C++, Etter/Ingber
Chapter 5: Loops and Files.
Chapter 4: Making Decisions.
Chapter 4: Control Structures I (Selection)
2.6 The if/else Selection Structure
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Chapter 3: Selection Structures: Making Decisions
Chapter 3: Selection Structures: Making Decisions
Selection Control Structure
Presentation transcript:

Chapter 4 Selection Structures: Making Decisions

4.1An Introduction to Selection Structures Single-alternative –A single block of statements to be executed or skipped Dual-alternative – Two blocks of statements, one of which is to be executed, while the other one is to be skipped Multiple-alternative –More than two blocks of statements, only one of which is to be executed and the rest skipped.

Single-alternative If something is true Then Do something ( any # of statements) End If If Age >= 18 set Eligibility = ‘Yes’ End if

Dual-alternative If something is true Then Do something Else Do something else End If If Age >= 18 set Eligibility = ‘Yes’ Else set Eligibility = ‘No’ End if

C++ Relational Operators Relational operators are the symbols used in the condition to be evaluated in If statements: ==equal to !=not equal to <less than >greater than <=less than or equal to >=greater than or equal to

Logical Operators Logical operators are used to connect simple conditions into a more complex condition called a ‘compound’ condition. The simple conditions each contain one relational operator. Using compound conditions reduces the amount of code that must be written. && Logical And ||Logical Or !Negation

Truth Tables for Boolean Operators Truth tables Logical operators !, ¦¦, && –1 is a symbol for true –0 is a symbol for false

Logical Operators Logical operator (&& means AND) used in an if...else statement: ( (tryIt >= 0) && (tryIt <= 100) ) ( tryIt >= 0 && tryIt <= 100 ) Logical operator (| | means OR) used in an if...else statement: ( (tryIt >= 0) | | (tryIt <= 100) ) (tryIt >= 0 | | tryIt <= 100 )

Using && Assume tryIt = 90, Is tryIt within the range of 0 and 100 ? ( (tryIt >= 0) && (tryIt <= 100) ) ( ( 90 >= 0) && ( 90 <= 100) ) ( 1 && 1 ) 1

Using && Assume tryIt = 99 Is tryIt outside the range of 0 and 100 ? ( (tryIt 100) ) ( ( ) ) ( 0 ¦¦ 0 ) 0

Example Pseudo Code Input X If (X 10) Then Write “OK” End If C++ Code int x; if ((x 10) ) cout << “OK”;

Hierarchy of Operations

4.3 Selecting from Several Alternatives Sometimes, we must handle more than two options in a program. If something is true Then Do something Else If something else is true Then Do something else Else Do a different something else End If

Write a program that ask user to input a number, if it is less than zero output message “Negative number” 1.Read a number 2.if number is less than 0 then 3. Write “Negative number” 4.end if End Output “Negative number” Is number < 0 Input number Start Yes No

C++ code short number = 0; cout << “Enter a number: “; cin >> number; if (number < 0) cout << “Negative number” << endl;

Write a program that displays a message “Negative number” if the number that user entered is less than zero or else it displays a message “Positive number”.. 1)Read a num 2)I f (the num is less than 0)Then Write“Negative number” else Write “Positive number” end if Stop Display “Positive number” num < 0 Enter a num Start Display “Negative number” F T

C++ code short number = 0; cout << “Enter a number: “; cin >> number; if (number < 0) cout << “Negative number” << endl; else cout << “Positive number” << endl;

Write a program that displays a message “Negative number” if the number that user entered is less than zero or it displays a message “Positive number” if number is greater than zero or it displays a message “Zero” if number is zero. 1)Read a num 2) if (the num is less than 0)Then Write “Negative number” else if(num is greater than 0)Then Write “Positive number” else Write “Zero” End if Stop Display “Zero” num < 0 enter num Staaar t Display “Negaative number” num > 0 Display “Positive number” FT F T

C++ code short number = 0; cout << “Enter a number: “; cin >> number; if (number < 0) cout << “Negative number” << endl; else if (number > 0) cout << “Positive number” << endl; else cout << “Zero” << endl;

Hints The number of ‘End If’s’ must equal the number of ‘If’s’. You can draw a line to connect them to check. Regardless of how many possible conditions are included, only one will ever be executed.

Expanding the C++ if Statement The if statement can conditionally execute a block of statement enclosed in braces. if (expression) { statement; // Place as many statements here as necessary. }

The C++ if/else Statement The if/else statement will execute one group of statements if the expression is true, or another group if the expression is false. if (expression) { block of statements; } else { block of statements; }

The C++ if/else if Construct The if/else if statement is a chain of if statements. The perform their tests, one after the other, until one of them is found to be true. if (expression) { block of statements; } else if (expression) { block of statements; } // put as many else if’s as needed here else if (expression) { block of statements; }

Case-type Statements ‘Case’ or ‘Switch’ statements can be used to more easily code multiple alternative ‘If’s’ Use the special or keyword ‘Case’. Use ‘Select’ to start the Case statement. Specify the expression to be evaluated. List each possible value of the expression and what to do if that is that value is the true one. Use ‘End Case’ to end the statement The results will be the same as a correctly code multiple-alternative ‘If’.

Example Select Case of Choice Case 1: Set Ops = ‘Add’ Case 2: Set Ops = ‘Subtract’ Case 3: Set Ops = ‘Multiply’ Case 4: Set Ops = ‘Divide’ End Case

4.4 Applications of Selection Structure (Input Validation) Program defensively in order to prevent bad data from entering our program. To do this, set error ‘traps’. If our program should accept only a Cost greater than 0, we can stop any other value from entering with the following trap: Input Cost If Cost <= 0 Then Write “Invalid cost” Else Write “The cost is ”, Cost End If

The C++ switch Statement The switch statement lets the value of a variable or expression determine where the program will branch to. pseudo code is in Venit p126 and flowchart is in Venit p113, P127

Program The switch statement in this program tells the user something // he or she already knows: what they just entered! #include using namespace std; int main() { 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"; } return 0; } #include using namespace std; int main() { char Choice; cout << "Enter A, B, or C: "; cin >> Choice; if (Choice == ‘A’) cout << "You entered A.\n"; else if(Choice == 'B’) cout << "You entered B.\n"; else if (Choice == 'C’) cout << "You entered C.\n"; else cout << "You did not enter A, B, or !\n"; return 0; }

Program Output with Example Input Enter A, B, or C: B [Enter] You entered B. Program Output with Different Example Input Enter a A, B, or C: F [Enter] You did not enter A, B, or C!

Program 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"; } #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; if (FeedGrade==‘a’ || FeedGrade == ‘A’) cout << "30 cents per pound.\n"; else if (FeedGrade==‘b’ || FeedGrade == ‘B’) cout << "20 cents per pound.\n"; else if (FeedGrade==‘c’ || FeedGrade == ‘C’) cout << "15 cents per pound.\n"; else cout << "That is an invalid”<< “choice.\n"; }

Defensive Programming Be sure to test your program by ‘playing computer’: Perform all calculations multiple times manually or with a calculator. Make sure each branch of each selection structure is executed at least once. Check for division by zero, negative values for a square root function, and any other special conditions.

Pseudocode Language (Ch 4) In this chapter we added logical operators and selection. InputAssignment Input Variable Set Variable = 10 OutputArithmetic Operations Write “literal text”, Variable ( ) ^ * / + - Relational OperatorsLogical Operators = <> >= <=And Or Not Repetition While conditionRepeat … End WhileUntil condition For Counter = InitialValue Step Increment To LimitValue End For Create a module Call a sub-module ModuleName Call ModuleName …. End Selection If condition Then Select Case of Else Case : End If Case : End Case