Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School

Similar documents
Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 4: Control Structures I (Selection)

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

C++ Programming: From Problem Analysis to Program Design, Third Edition

Information Science 1

Chapter 4 - Notes Control Structures I (Selection)

Information Science 1

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Relational Operators and if. Class 10

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

QUIZ: What value is stored in a after this

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Topics. Chapter 5. Equality Operators

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

UNIT- 3 Introduction to C++

The following expression causes a divide by zero error:

Chapter 3. More Flow of Control

Introduction to Programming

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Checking Multiple Conditions

4. Logical Values. Our Goal. Boolean Values in Mathematics. The Type bool in C++

Chapter 4: Making Decisions

Chapter 4: Making Decisions

CSI33 Data Structures

Decision Making -Branching. Class Incharge: S. Sasirekha

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Increment and the While. Class 15

BRANCHING if-else statements

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

5. Selection: If and Switch Controls

STUDENT LESSON A12 Iterations

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

UEE1302(1102) F10: Introduction to Computers and Programming

Problem Solving with C++

3. Logical Values. Our Goal. Boolean Values in Mathematics. The Type bool in C++

[Ch 6] Set Theory. 1. Basic Concepts and Definitions. 400 lecture note #4. 1) Basics

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Chapter 3. Selections

CSCE 206: Structured Programming in C++

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

5. Control Statements

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Chapter 7. Additional Control Structures

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Add Subtract Multiply Divide

LECTURE 04 MAKING DECISIONS

Programming, numerics and optimization

Review. Relational Operators. The if Statement. CS 151 Review #4

Logical Operators and switch

Absolute C++ Walter Savitch

ITP 342 Mobile App Dev. Code

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

Other Loop Options EXAMPLE

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

LESSON 3 CONTROL STRUCTURES

VARIABLES & ASSIGNMENTS

Chapter 2 - Control Structures

REVIEW. The C++ Programming Language. CS 151 Review #2

bool bool - either true or false

Chapter 2 - Introduction to C Programming

Computer Programming : C++

More Complex Versions of the if Statement. Class 13

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

CS 105 Lecture 5 Logical Operators; Switch Statement. Wed, Feb 16, 2011, 5:11 pm

Functions. Lecture 6 COP 3014 Spring February 11, 2018

C++ Program Flow Control: Selection

INTERNATIONAL EDITION. Problem Solving with C++ Data Abstraction & SIXTH EDITION. Walls and Mirrors. Frank M. Carrano Timothy Henry

CHAPTER 3 BASIC INSTRUCTION OF C++

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Control Structures in Java if-else and switch

conditional statements

Chapter 2 Basic Elements of C++

COMP322 - Introduction to C++ Lecture 01 - Introduction

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Announcements. HW0 is posted on schedule, due next Friday at 9pm (pretty easy)

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Homework #3 CS2255 Fall 2012

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

C: How to Program. Week /Mar/05

Transcription:

Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School

Objectives Construct and evaluate Boolean expressions Understand how to use selection statements to make decisions Design and test if statements Design and test if-else statements Design and test switch statements Dave Clausen 2

Boolean Expressions Selection Statements a control statement that help the computer make decisions Certain code is executed when the condition is true, other code is executed or ignored when the condition is false. Control Structure controls the flow of instructions that are executed. Dave Clausen 3

New Data Type Simple data types that we already know int, double, char New simple type bool (Boolean data type: true or false) bool is_prime = false; if (is_prime = = true) //not necessary to test if (is_prime) //preferred: is_prime contains true of false Dave Clausen 4

Boolean Data Type In older systems BOOLTEST_Dev.cpp 0 represents false the number 1 represents true assign values of true or false in lowercase letters Dave Clausen 5

Relational Operators, and Boolean Expressions Relational Operators operations used on same data types for comparison equality, inequality, less than, greater than Simple Boolean Expression two values being compared with a single relational operator has a value of true or false Dave Clausen 6

Relational Operators Arithmetic Operation = < > Meaning Is equal to Is less than Is greater than less than or equal to greater than or equal to Is not equal to Relational Operator = = < > <= >=!= Dave Clausen 7

Simple Boolean Expressions 7 = = 7-3.0 = = 0.0 4.2 > 3.7-18 < -15 13 < 0.013-17.32!= -17.32 a = = a true false true true false false true Dave Clausen 8

Order of Operations 1. ( ) 2. *, /, % 3. +, - 4. = =, <, >, <=, >=,!= Dave Clausen 9

Comparing Strings Compared according to ASCII values upper case < lower case (i.e. A < a is true) When comparing 2 strings where one is a subset of the other (one string is shorter & contains all the same letters) shorter string < longer string i.e. Alex < Alexander Dave Clausen 10

Confusing = and = = = = means equality in a comparison = means assigning a value to an identifier side effects are caused if we confuse the two operators P209EX1Dev.cpp Dave Clausen 11

Compound Boolean Expressions Logical Operators And && (two ampersands) Conjunction Or (two pipe symbols) Disjunction Not! (one exclamation point) Negation Use parentheses for each simple expression and the logical operator between the two parenthetical expressions. i.e. ((grade >= 80) && (grade < 90)) Dave Clausen 12

Truth Tables for AND / OR Expression1 Expression2 E1&&E2 E1 E2 (E1) (E2) true true true true true false false true false true false true false false false false Dave Clausen 13

Truth Table for NOT Order of Priority for Booleans Expression Not E (E)!E true false false true Order Of Priority in Boolean Expressions 1.! 2. && 3. Dave Clausen 14

Order of Operations including Booleans 1. ( ) 2.! 3. *, /, % 4. +, - 5. <, <=, >, >=, = =,!= 6. && 7. Dave Clausen 15

Complements Operation! <! <=! >! >= Complement (equivalent) >= > <= < Dave Clausen 16

DeMorgan s Laws! ( A && B) is the same as:!a!b Not (true AND true) Not(true) OR Not(true) Not (true) false OR false false false!( A B) is the same as:!a &&!B Not( true OR true) Not(true) AND Not(true) Not (true) false AND false false false Dave Clausen 17

If Statements Format for if statements: if (<Boolean expression>) <statement> Parentheses are required around the Boolean Expression. sum = 0.0; cin>>number; if (number > 0.0) sum = sum + number; cout<< the sum is: <<sum<<endl; Dave Clausen 18

Compound Statements Use the symbols { and } to group several statements as a single unit. Simple statements within the compound statements end with semicolons. Compound Statements are sometimes called a statement block. Use compound statements in an if statement if you want several actions executed when the Boolean expression is true. MINMAXDev.cpp Dave Clausen 19

if else Statements Format for if else statements if (<Boolean expression>) { <true statement> //end of if option } else { <false statement> //end of else option } Dave Clausen 20

if else Example cout<< Please enter a number and press <Enter>. ; cin>>number; if (number < 0) { neg_count = neg_count + 1; cout<<setw(15) << number<<endl; //end if option } else { non_neg_count = non_neg_count + 1; cout << setw(30) << number << endl; //end of else option } Dave Clausen 21

Behavior of Selection Statements if (<Boolean expression>) { <statement 1>. <statement n> } true? statement false if (<Boolean expression>) <statement> else { <statement 1>. <statement n> } true? false statement statement Dave Clausen 22

Robust Programs Robust Programs are protected from: most possible crashes bad data unexpected values For student programs balance error trapping and code efficiency our text assumes valid data is entered when requested. Dave Clausen 23

Nested if statements Nested if statement (avoid this for this class) an if statement used within another if statement where the true statement or action is. if (score >=50) else if (score>=69.9) else cout<<blah, blah, blah //true for score>=69.9 and score>=50 cout<<blah, blah, blah //false score>=69.9 true score >=50 cout<<blah, blah, blah //false for score >=50 Dave Clausen 24

Extended if statements Extended if statements are Nested if statements where another if statement is used with the else clause of the original if statement. (use this for this class) if (condition 1) action1 else if (condition2) action2 else action3 Dave Clausen 25

Avoid Sequential Selection This is not a good programming practice. Less efficient only one of the conditions can be true this is called mutually exclusive conditions if (condition1) //avoid this structure action1 //use nested selection if (condition2) action2 SALESDev.cpp if (condition3) action3 Dave Clausen 26

Program Testing Use test data that tests every branch or selection in the program. Test the if statement(s) Test the else statement(s) Test the border, edge, extreme cases. Test carefully nested and extended selection statements and their paths. Dave Clausen 27

Switch Statements Allows for multiple selection that is easier to follow than nested or extended if statements. switch (age) { } case 18: case 19: case 20: default: //age is of type int <statement1> break; <statement2> break; <statement3> break; <default statement> Dave Clausen 28

Switch: Flow of Execution The selector (argument) for switch must be of an ordinal type (not double) switch (age) The variable age is called the selector in our example. If the first instance of the variable is found among the labels, the statement(s) following this value is executed until reaching the next break statement. Program control is then transferred to the next statement following the entire switch statement. If no value is found, the default statement is executed. Dave Clausen 29

Switch Statement Example 2 switch (grade) { case A : case B : case C : case D : case F : default : } //grade is of type char cout<< Good work! <<endl; break; cout<< Average work <<endl; break; cout<< Poor work <<endl; break; cout<<grade<< is not a valid letter grade. ; break; Dave Clausen 30

Assertions Assertions A statement about what we expect to be true at a certain point in the program where the assertion is placed. Could be used with selection, functions, and repetition to state what you expect to happen when certain conditions are true. Could be comments, should be Boolean expressions that could be evaluated by the compiler. Are used as preconditions and post conditions Can be used as a proof of your program s correctness Can help you debug your program. If there is an error, the program halts with an error message and the line number where the error is located. Dave Clausen 31

Implementing Assertions Use #include <cassert> Example 1: assert (number_of_students!= 0); class_average = sum_of_scores / number_of_students; The parameter of assert is a Boolean Expression. The compiler verifies if the assertion is true or false if false, the program halts with an error message: Assertion Failed: number_of_students!=0, file filename, line 48 this tells you that your assertion is false Dave Clausen 32

Assertion Example #2 Assertions used as pre & post conditions: assert((num1>=0) && (num2>=0)); //precondition if (num1 < num2) { temp = num1; num1 = num2; num2 = temp; } assert((num1>=num2) && (num2>=0)); //postcondition Dave Clausen 33

Assert as a Debugging Tool Executable assertions when false, terminate your program and tell you the line number where the error is located. This is valuable during the software debugging and testing phases. When your program is working correctly, you do not need to remove all the assertions manually. Add the preprocessor directive: #define NDEBUG #include <cassert> BEFORE //NDEBUG means No debug. assertdev.cpp to ignore all assert functions. Dave Clausen 34