UEE1302(1102) F10: Introduction to Computers and Programming

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

Chapter 4: Control Structures I (Selection)

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

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

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

Chapter 4 - Notes Control Structures I (Selection)

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

Chapter 4: Control Structures I

Topics. Chapter 5. Equality Operators

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages

5. Selection: If and Switch Controls

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

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

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

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

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

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

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

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

Chapter 4: Making Decisions

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

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

Selection Statements. Pseudocode

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

UNIT- 3 Introduction to C++

LECTURE 04 MAKING DECISIONS

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

Chapter 2. C++ Basics

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter 3 Selection Statements

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

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Computer Science & Engineering 150A Problem Solving Using Computers

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.

UEE1302 (1102) F10: Introduction to Computers and Programming

Chapter 7. Additional Control Structures

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

Absolute C++ Walter Savitch

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

conditional statements

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

CSI33 Data Structures

Chapter 4 : Selection (pp )

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

Computer Programming : C++

C++ Program Flow Control: Selection

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

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Lecture 3 Tao Wang 1

CSCI 1061U Programming Workshop 2. C++ Basics

Review of the C Programming Language for Principles of Operating Systems

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

Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

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

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

Introduction to Programming using C++

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Relational Operators and if. Class 10

Control Structures in Java if-else and switch

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

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

Chapter 3. Selections

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

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

Programming, numerics and optimization

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

Object-Oriented Programming

Add Subtract Multiply Divide

Repetition Structures

Objectives. In this chapter, you will:

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

Decisions. Arizona State University 1

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Chapter 2 - Control Structures

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Control Structures in Java if-else and switch

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

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

1 Lexical Considerations

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

Conditionals. CSE / ENGR 142 Programming I. Chapter 4. Conditional Execution. Conditional ("if ") Statement. Conditional Expressions

BITG 1233: Introduction to C++

Conditions, logical expressions, and selection. Introduction to control structures

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 4

Control Structures: The IF statement!

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

QUIZ: What value is stored in a after this

Loops and Files. of do-while loop

Chapter 3. More Flow of Control

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Transcription:

Computational Intelligence on Automation Lab @ NCTU UEE1302(1102) F10: Introduction to Computers and Programming Programming Lecture 02 Flow of Control (I): Boolean Expression and Selection Learning Objectives You should be able to describe: Relational Expressions Logical Expressions if- Statement Nested if and if Chain Statements switch Statement Common Programming Errors PRO_02 PROF. HUNG-PIN(CHARLES) WEN 2 Control Structures Flow of Control: the order in which a program s statements are executed Normal flow is sequential Selection and Repetition statements allow programmer to alter normal flow Selection: selects a particular statement to be executed next selection is from a well-defined set Repetition: allows a set of statements to be repeated statement 1 statement 2 statement N Flow of Execution false stmt_no bool_expr true stmt_yes true stop_cond false stmt_loop (A) sequence (B) selection (C) repetition PRO_02 PROF. HUNG-PIN(CHARLES) WEN 3 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 4

Relational Expressions All computers are able to compare numbers can be used to create an intelligence-like facility Relational Expressions: expressions used to compare operands format: a relational operator connecting 2 variables and/or constant operands examples of valid relational expressions: age > 40 length <= 50 flag == done PRO_02 PROF. HUNG-PIN(CHARLES) WEN 5 Math Relational Operators (1/2) meaning C++ notation Example = Equal to == 2*x == 7*y Not equal to!= ans!= n > Greater than > income > 50000 Greater than or equal to >= age >= 18 < Less than < count < base + 10 Less than or equal to <= height <= 170 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 6 Relational Operators (2/2) Relational Expressions (conditions): are evaluated to yield a numerical result condition that is true evaluates to 1 condition that is false evaluates to 0 Example: The relationship 2.0>3.3 is always false, therefore the expression has a value of 0 Logical Operators (1/2) More complex conditions can be created using basic logical operations AND symbol: &&, OR symbol : NOT symbol :! AND operator, &&: Used with 2 simple expressions Example: (age > 40) && (term < 10) Compound condition is true (has value of 1) only if age > 40 and term < 10 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 7 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 8

Logical Operators (2/2) OR operator, : Used with two simple expressions Example: (age > 40) (term < 10) Compound condition is true if age > 40 or if term < 10 or if both conditions are true NOT operator,!: Changes an expression to its opposite state If expr_a is true, then!expr_a is false Precedence of Operations Operator!(unary),, ++, Associativity right to left *, /, % left to right +, left to right <, <=, >, >= left to right ==,!= left to right && left to right left to right =, +=, =, *=, /= right to left PRO_02 PROF. HUNG-PIN(CHARLES) WEN 9 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 10 Precedence Examples Arithmetic before logical x + 1 > 2 x + 1 < -3 means (x + 1) > 2 (x + 1) < -3 Short-circuit evaluation (x >= 0) && (y > 1) Be careful with increment operators! Ex:(x > 1) && (y++) Integers as Boolean values All non-zero values true Zero value false PRO_02 PROF. HUNG-PIN(CHARLES) WEN 11 DeMorgan's Laws Two propositional logic rules negation of conjunction : (A B) = A B negation of disjunction : (A B) = A B Suppose A and B are logical expressions!(a && B) (!A) (!B)!(A B) (!A) && (!B) Principle of double negation!(!a) A Example:!(YourAge < Min YourAge > Max) (YourAge >= Min && YourAge <= Max) PRO_02 PROF. HUNG-PIN(CHARLES) WEN 12

Selection (I): One-Way if Example of One-Way if false decision_ maker true action_stmt Formal syntax of one-way selection : if (decision_maker) //no ; here action_stmt; decision_maker : is a logical expression decides whether to execute the action statement if decision_maker is true, execute action_stmt if decision_maker is false, bypass action_stmt Example 1: if (score >= 90) grade = A ; Example 2: absolute value if (ivar < 0) ivar = -ivar; cout << absolute value = << ivar << endl; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 13 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 14 Selection (I): Two-Way if- Choice of two alternate statements based on condition expression Formal syntax : if (decision_maker) // no semicolon here action_stmt_yes; // no semicolon here action_stmt_no; decision_maker: decide which one of two statements to run if the evaluation is true, run action_stmt_yes if the evaluation is false, run action_stmt_no Example of Two-Way if- Example 1: pass or fail if (score >= 60) cout << Pass << endl; cout << Fail << endl; Example 2: overtime payment if (hours > 40) pay = rate*40 + 1.5*rate*(hours-40); pay = rate*hours; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 15 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 16

Compound Statement What if we want to execute multiple statements in action? Compound statement ( a.k.a. a block of statements): { statement 1; statement 2; statement n; } a compound statement is treated as a single statement Example of Compound Statements if (age >= 18) { } { } cout << "Eligible to vote." << endl; cout << "No longer a minor." << endl; cout << "Not eligible to vote. << endl; cout << "Still a minor." << endl; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 17 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 18 Nested if Nesting: one control statement in another An is associated with the most recent if that has not been paired with an Example 1: Tax Computation if (income > 5000000.0) tax = income * 0.50; if (income > 1000000.0) tax = income * 0.30; if (income > 500000.0) tax = income * 0.20; tax = income * 0.10; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 19 p21 Avoid Excessive Indentation Use if chain instead of nested if Example 2: Grading if (score >= 80.0) grade = A ; if (score >= 70.0) grade = B ; if (score >= 60.0) grade = C ; grade = F ; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 20

Compare if Chain and Multiple if Question: What s the difference?? if Chain if (month == 1) cout<< Jan <<endl; if (month == 2) cout<< Feb <<endl; if (month == 3) cout<< Mar <<endl; eles if (month == 11) cout<< Nov <<endl; cout<< Dec <<endl; Multiple if if (month == 1) cout<< Jan <<endl; if (month == 2) cout<< Feb <<endl; if (month == 3) cout<< Mar <<endl; if (month == 11) cout<< Nov <<endl; if (month == 12) cout<< Dec <<endl; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 21 Common Pitfalls on if- Operator "=" vs. operator "==" "assignment versus equality" Example: What s the problem?? if (age = 20) cout<< Happy 20-year old birthday <<endl; Using = instead of == in the if- statement causes the most difficult errors Hard to debug due to no error message Nested if statements needs braces {} to clearly indicate the desired structure PRO_02 PROF. HUNG-PIN(CHARLES) WEN 22 Selection (II):?: Selection (III): switch (1/2) Conditional operator (?:?:) takes three arguments (ternary) equivalent to if- Syntax for the conditional operator: var = expr_1? expr_2 : expr_3; if expr_1 is true, assign expr_2 to var if expr_1 is false, assign expr_3 to var Ex: bool taxable = (age >=18)? true:false; Exercise: how to rewrite the tax computation example by using (?:) PRO_02 PROF. HUNG-PIN(CHARLES) WEN 23 A new stmt for controlling multiple branches Syntax format: switch ( control_expr ) { // start of compound statement case literal_1 : //<-terminated with a colon statement_1; statement_2; case literal_2 : //<-terminated with a colon statement_3; default : //<-terminated with a colon statement_n; } // end of switch and compound stmt PRO_02 PROF. HUNG-PIN(CHARLES) WEN 24

Selection (III): switch (2/2) Rewrite Month Example Four new keywords used: switch, case, default and break Function: control_expr following switch is evaluated must compare to an literal Result compared sequentially to alternative case values until a match is found Statements following matched case are executed When break reached, switch terminates If no match found, run default statement block Using if Chain if (month == 1) cout<< Jan <<endl; if (month == 2) cout<< Feb <<endl; if (month == 3) cout<< Mar <<endl; eles if (month == 11) cout<< Nov <<endl; cout<< Dec <<endl; Using switch switch (month) { case 1: cout<< Jan <<endl; case 2: cout<< Feb <<endl; case 11: cout<< Nov <<endl; default: cout<< Dec <<endl; } PRO_02 PROF. HUNG-PIN(CHARLES) WEN 25 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 26 Common Pitfalls on switch Forgetting No compiler error Execution simply falls through other cases until Ex: if month is equal to 13 in the previous example, screen still displays " Dec" Best usage: Menus Provides clearer big-picture view Shows menu structure effectively Each branch is one menu choice switch Menu Example switch (response) { case 1 : // Execute menu option 1 case 2 : // Execute menu option 2 case 3 : // Execute menu option 3 default: cerr << "Please enter a valid response."; } Good habit to enumerate all known cases and prompt by cerr if unknown case occurs PRO_02 PROF. HUNG-PIN(CHARLES) WEN 27 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 28

Cable Bill Exercise This programming exercise calculates a customer s bill for a local cable company Residential customer rates: Bill processing fee: $4.50 Basic service fee: $20.50 Premium channel: $7.50 per channel Business customer rates: Bill processing fee: $15.00 Basic service fee: $75.00 for first 10 connections and $5.00 for each additional connection Premium channel cost: $50.00 per channel for any number of connections Requirements Ask user for account number and customer code Assume R or r stands for residential customer and B or b stands for business customer PRO_02 PROF. HUNG-PIN(CHARLES) WEN 29 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 30 Input: Input and Output Customer account number Customer code Number of premium channels For business customers, number of basic service connections Output: Customer s account number Billing amount Program Analysis (1/2) The purpose of the program is to calculate and print billing amount Calculating the billing amount requires: Customer for whom the billing amount is calculated (residential or business) Number of premium channels to which the customer subscribes For a business customer, you need: Number of basic service connections Number of premium channels PRO_02 PROF. HUNG-PIN(CHARLES) WEN 31 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 32

Program Analysis (2/2) Data needed to calculate the bill, such as bill processing fees and the cost of a premium channel, are known quantities The program should print the billing amount to two decimal places PRO_02 PROF. HUNG-PIN(CHARLES) WEN 33 Algorithm Design Set precision to two decimal places Prompt user for account number and customer type If customer type is R or r Prompt user for number of premium channels Compute and print the bill If customer type is B or b Prompt user for number of basic service connections and number of premium channels Compute and print the bill PRO_02 PROF. HUNG-PIN(CHARLES) WEN 34 Variables // variable to store customer s account # int accountnumber; // variable to store customer code char customertype; // variable to store # of subscribed // premium channels int numofpremchannels; // variable to store # of basi // connections int numofbasicservconn; Named Constants // for residential customers const double RES_BILL_PROC_FEES = 4.50; const double RES_BASIC_SERV_COST = 20.50; const double RES_COST_PREM_CHANNEL = 7.50; // for business customers const double BUS_BILL_PROC_FEES = 15.00; const double BUS_BASIC_SERV_COST = 75.00; const double BUS_BASIC_CONN_COST = 5.00; const double BUS_COST_PREM_CHANNEL = 50.00; // variable to store the billing amount double amountdue; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 35 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 36

Residential customers: Bill Formulas (1/2) Business customers: Bill Formulas (2/2) amountdue = RES_BILL_PROC_FEES + RES_BASIC_SERV_COST + numofpremchannels * RES_COST_PREM_CHANNEL; if (numofbasicservconn <= 10) amountdue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + numofpremchannels * BUS_COST_PREM_CHANNEL; amountdue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + (numofbasicservconn - 10) * BUS_BASIC_CONN_COST + numofpremchannels * BUS_COST_PREM_CHANNEL; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 37 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 38 Main Algorithm (1/3) 1. Output floating-point numbers in fixed decimal with decimal point and trailing zeros Output floating-point numbers with two decimal places set the precision to two decimal places 2. Prompt user to enter account number 3. Get customer account number 4. Prompt user to enter customer code 5. Get customer code (r, R, b, or B) Main Algorithm (2/3) 6. If the customer code is r or R, Prompt user to enter number of premium channels Get the number of premium channels Calculate the billing amount Print account number and billing amount PRO_02 PROF. HUNG-PIN(CHARLES) WEN 39 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 40

Main Algorithm (3/3) 7. If customer code is b or B, Prompt user to enter number of basic service connections Get number of basic service connections Prompt user to enter number of premium channels Get number of premium channels Calculate billing amount Print account number and billing amount 8. If customer code is other than r, R, b, or B, output an error message and exit. PRO_02 PROF. HUNG-PIN(CHARLES) WEN 41 Summary (1/3) Boolean expressions can be composed of relational and/or logical operations Relational Expressions (conditions): Are used to compare operands A condition that is true has a value of 1 A condition that is false has a value of 0 More complex conditions can be constructed from relational expressions using logical operators, && (AND), (OR), and! (NOT) Apply DeMorgan s Law properly PRO_02 PROF. HUNG-PIN(CHARLES) WEN 42 Summary (2/3) if- statements select between two alternative statements based on the value of an expression if- statements can contain other if- statements nested if If braces are not used, each statement is associated with the closest unpaired if if chain: a multi-way selection statement Each statement (except for the final ) is another if- statement Compound statement: any # of individual statements enclosed within braces {} PRO_02 PROF. HUNG-PIN(CHARLES) WEN 43 Summary (3/3) Condition operator (?:): equivalent to if- Ternary: takes three arguments switch statement: multi-way selection the value of an integer expression is compared to a sequence of integer or character constants or constant expressions (literals) program execution transferred to first matching case execution continues until optional break statement is encountered PRO_02 PROF. HUNG-PIN(CHARLES) WEN 44