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

Similar documents
Chapter 4 - Notes Control Structures I (Selection)

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

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

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

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

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

Chapter 4: Control Structures I

Chapter 4: Control Structures I (Selection)

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

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

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

Chapter 2. C++ Basics

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array

conditional statements

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

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

5. Selection: If and Switch Controls

Objectives. In this chapter, you will:

Object Oriented Pragramming (22316)

Lecture 5 Tao Wang 1

Programming Logic and Design Sixth Edition

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

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

Checking Multiple Conditions

Chapter 3 Problem Solving and the Computer

Fundamentals of Programming CS-110. Lecture 2

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

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

The following expression causes a divide by zero error:

Introduction to Programming EC-105. Lecture 2

More Complex Versions of the if Statement. Class 13

Boolean Algebra Boolean Algebra

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

C++ Program Flow Control: Selection

QUIZ: What value is stored in a after this

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.

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

If Control Construct

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

REPETITION CONTROL STRUCTURE LOGO

CSI33 Data Structures

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

Computer Programming : C++

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

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.

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

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

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

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

The births of the generations are as follow. First generation, 1945 machine language Second generation, mid 1950s assembly language.

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

An Introduction to Programming with C++ Sixth Edition. Chapter 8 More on the Repetition Structure

Section we will not cover section 2.11 feel free to read it on your own

Chapter 3. More Flow of Control

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

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

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

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

In this chapter, you will:

Starting Out With C++: Early Objects, Seventh Edition Solutions to End-of-Chapter Review Questions

Add Subtract Multiply Divide

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Topics. Chapter 5. Equality Operators

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

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

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

Increment and the While. Class 15

Decision Structures. Lesson 03 MIT 11053, Fundamentals of Programming

Chapter 4: Making Decisions

Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

WARM UP LESSONS BARE BASICS

Chapter 4: Making Decisions

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

LECTURE 04 MAKING DECISIONS

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

CHAPTER : 9 FLOW OF CONTROL

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

UEE1302(1102) F10: Introduction to Computers and Programming

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Chapter 2: Basic Elements of C++

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

Chapter Goals. 3.1 The if Statement. Contents 1/30/2013 DECISIONS

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each.

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Test Bank for Problem Solving with C++: The Object of Programming, 8/e Chapter 2 C++ Basics

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Chapter 4 : Selection (pp )

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Chapter 3 Structure of a C Program

Lecture 3 Tao Wang 1

LAB: WHILE LOOPS IN C++

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

Chapter 2 Working with Data Types and Operators

A First Program - Greeting.cpp

Transcription:

Lesson Outcomes At the end of this chapter, student should be able to: Use the relational operator (>, >=, <, <=, ==,!=) Use the logical operator (!, &&, ) Understand the Boolean expression Write the pseudocode for the selection structure Create flowchart for the selection structure Implement decision using one-way, two-ways, and multiple-ways selection structure (if, if, if--if) Recognize the correct ordering of decisions in multiple branches Program simple and complex decision 1

1. Comparison and Expression To make decisions, you must be able to make comparisons and express the conditions that are true or false. Comparison is done by using relational operator. i.e. i > j, x == y, etc. An expression that has a value either true or false is called a logical (Boolean) expression. Condition is represented by a logical (Boolean) expression. 2. Relational and Logical Operator 1. Relational Operator There are 6 relational operators that allow to state conditions and make comparisons. They are all binary operations that accept 2 operands and compare them. The result is logical data, that is, it is always true (1) or false (0). Relational Operator Meaning < Less than <= Less or equal > Greater >= Greater or equal == Equal!= No equal 2. Logical Operator Logical operators enable you to combine logical expressions. C++ has three logical operators as below: Operator Description! not && and or Logical operators take only logical values as operands and produce only logical values as result. The operator! is unary, so it has only one operand. The operator && and are binary operators, so it has more than one operand. 2

3. Simple Boolean Expression An expression in which two numbers (arithmetic values) is compared using a single relational operator. Each Boolean expression has the Boolean value true or false according to the arithmetic validity of the expression: Syntax of Boolean expression: <arithmetic value> relational operator <arithmetic value> Boolean value Example of Boolean expression using relational operator: Expression Meaning Value 8 < 15 8 is less than 15 True 6!= 6 6 is not equal to 6 False 2.5 > 5.8 2.5 is greater than 5.8 False 5.9 <= 7.5 5.9 is less than or equal to 7.5 True 1. The! (not) Operator Expression: Expression!(Expression) true (1) false (0) false (0) true (1) Example: Expression Value Explanation! ( A > B ) true Because A > B is false,! ( A > B ) is true! (6 <= 7) false Because 6 <= 7 is true,! (6 <= 7) is false 2. The && (and) operator Expression: Expression1 Expression2 Expression1 && Expression2 true (1) true (1) true (1) true (1) false (0) false (0) false (0) true (1) false (0) false (0) false (0) false (0) 3

Example: Expression Value Explanation (14 >= 5) && ( A < B ) true Because (14 > = 5) is true, ( A < B ) is true, and true && true is true, the expression evaluates to true. (24 >= 35) && ( A < B ) false Because (24 >= 35) is false, ( A < B ) is true, and false && true is false, the expression evaluates to false. 3. The (or) operator Expression: Expression1 Expression2 Expression1 Expression2 true (1) true (1) true (1) true (1) false (0) true (1) false (0) true (1) true (1) false (0) false (0) false (0) Example: Expression Value Explanation (14 >= 5) ( A > B ) true Because (14 > = 5) is true, ( A > B ) is false, and true false is true, the expression evaluates to true. (24 >= 35) ( A > B ) false Because (24 >= 35) is false, ( A > B ) is false, and false && false is false, the expression evaluates to false. ( A <= a ) (7!=7) true Because ( A <= a ) is true, (7!=7) false, and true false is true, the expression is evaluates to true. 4. Precedence of Operator Operators Precedence ++, -- First!, +, - (unary operators) Second *, /, % Third +, - (binary operator) Fourth <, <=, >=, > Fifth ==,!= Sixth && Seventh Eighth = (assignment operator) Last 4

5. Decision Control Structure The program executes particular statements depending on some condition(s). This structure represents decision-making capabilities of the computer. You can use selection control structure in pseudocode/flowchart to illustrate a choice between two or more actions, depending on whether a condition is true or false. There a number of variations of the selection structures, as follows: 1. One-way selection a. Simple selection with null false branch (null ELSE statement) 2. Two-ways selection a. Simple selection (if- statement) b. Combined selection i. && (AND) ii. OR 3. Multi-ways (multiple) selection a. Linear nested if statement b. Non-linear nested if statement c. Switch statement 5

1. One Way Selection The null ELSE structure is a variation of the simple IF structure. It used when a task is performed only when a particular condition is true. If the condition is false, then no processing will take place and the IF statement will be passed. Syntax: if (expression) Statement Example: #include <math.h> #include <conio.h> int absolutevalue, negativenumber; getch(); cout << "Enter negative number : "; cin >> negativenumber; if (negativenumber < 0) absolutevalue = fabs(negativenumber); cout << "Absolute value for " << negativenumber << " is " << absolutevalue; 2. Two Way Selection a. Simple selection (if-) Simple selection occurs when a choice is made between two alternative paths, depending on the result of a condition being true or false. Only one of the selection will be followed, depending on the result of the condition in the IF clause. Syntax: if (expression) statement1 statement2 6

Example: double wages, rate, hours; cout << Enter working hours and rate ; cin >> hours >> rate; if (hours > 40.0) wages = 40.0 * rate + 1.5 * rate * (hours 40.0); wages = hours * rate; cout << The wages are RM << wages; b. Combined selection A combined IF statement is one which contains multiple conditions, each connected with the logical operators AND and OR. If the condition are combined using the connector AND, then both conditions must be true for the combined condition to be true. If the connector OR is used to combine any two conditions, then only one of the conditions needs to be true for the combined condition to be considered true. If neither condition is true, then the combined condition is considered false. Example of program using && (AND) selection int number = 2; //global variable int main () if (number > 0 && number % 2 == 0) cout << "Number is positive and even"; cout << Number is negative and odd ; 7

Example of program using (OR) int main () int number = 2; if (number > 0 number % 2 == 0) cout << "Number is positive or even"; cout << Number is negative and odd ; 3. Multiway Selection a. Linear nested if statement Linear IF statement is used when a field is being tested various values and a different action is to be taken for each value. This form of nested IF is called linear because each ELSE immediately follows the IF condition to which it corresponds, Comparisons are made until next ELSE statement is reached. Example program: Syntax: if (condition1) Statement1 if (condition2) Statement2 Statement3 double balance, dividendrate; cout << "\n What is your balance? "; cout << "\n Balance RM "; cin >> balance; if (balance > 5000.00) dividendrate = 0.07; if (balance >= 2500.00) dividendrate = 0.05; if (balance >= 1000.00) dividendrate = 0.03; 8

dividendrate = 0.00; cout << "\n Your dividend rate is RM " << dividendrate ; b. Non-linear nested if statement A non-linear nested IF occurs when a number of different conditions need to be satisfied before a particular action can occur. It called non-linear because the ELSE statement may be separated from the IF statement with which it is paired. Each ELSE statement should be aligned with the IF condition to which it corresponds. Syntax: if (condition1) if (condition2) Statement1 Statement2 Example of program: char gender; int age; double policyrate; cout << "\n What is your gender and age? "; cout << "\n gender (M/F) "; cin >> gender; cout << "\n age "; cin >> age; if (gender == 'M' gender == 'm') // if (toupper(gender) == M ) if (age < 21) policyrate = 0.05; policyrate = 0.035; if (gender == F gender == f ) if (age < 21) policyrate = 0.04; policyrate = 0.03; cout << "\n Your policy rate is RM " << policyrate; 9

4. Compound (Block of) Statement for Selection Structure a. Why compound statement The if and if structures control only one statement at a time. Suppose you want to execute more than one statement if the expression in an if or if statement evaluates to true, C++ provides a structure called compound statement or a block of statements. A compound statement consist of sequence of statements enclosed in curly braces, and. In an in if or if structure, a compound statement functions as if it was a single statement. A compound statements takes the following syntax form: if (condition1) statement1 statement2 statementn Example of program for compound statement char gender; int age; double policyrate; cout << "\n What is your gender and age? "; cout << "\n gender (M F) "; cin >> gender; cout << "\n age "; cin >> age; if (gender == 'M' gender == 'm') if (age < 21) policyrate = 0.05; cout << "\n Your policy rate is RM " << policyrate; policyrate = 0.035; cout << "\n Your policy rate is RM " << policyrate; 10

if (gender == F gender == f ) if (age < 21) policyrate = 0.04; cout << "\n Your policy rate is RM " << policyrate; policyrate = 0.03; cout << "\n Your policy rate is RM " << policyrate; cout << Unidentified code ; Multiway Selections (Switch statement) switch statement is an alternative method for multiple selections. It is often used to replace the nested if statement to avoid confusion of deeply nested ifs. switch statement only evaluates an integer expression or a character constant value. Syntax form: switch (expression) case value1: statement1; case value2: statement2; case valuen: statementn; default: default statement; //optional 11

Flowchart expression value1 value2 valuen default statement1 Statement2 statementn default statement break break break 12

Comparison of if and switch statement 1. Using integer expression if- statement switch statement #include <iostream> int code; cout << Enter code (1, 2, 3 or 4): cin >> code; if (code == 1) cout << Diploma in Computer Science ; if (code == 2) cout << Diploma in Accountancy ; if (code == 3) cout << Diploma in Business Study ; if (code == 4) cout << Diploma in Banking ; cout << Error in filling code ; cout << \n End of Program. ; #include <iostream> int code; cout << Enter code (1, 2, 3 or 4): cin >> code; switch (code) case 1 : cout << Diploma in Computer Science ; case 2 : cout << Diploma in Accountancy ; case 3 : cout << Diploma in Business Study ; case 4 : cout << Diploma in Banking ; default : cout << Error in filling code ; cout << \n End of Program. ; 2. Using character constant if- statement char code; cout << Enter code (G, Y, or R): cin >> code; if (code == G code == g ) cout << GREEN ; if (code == Y code == y ) cout << YELLOW ; if (code == R code == r ) cout << RED ; cout << Error in filling code ; cout << \n End of Program. ; switch statement char code; cout << Enter code (G, Y, or R): cin >> code; switch (code) case G : case g : cout << GREEN ; case Y : case y : cout << YELLOW ; case R : case r : cout << RED ; default : cout << Error in filling code ; cout << \n End of Program. ; 13

String Comparison In C++, c-strings are compared character-by-character using the system s collating sequence. Predefined function that can be used in C++ to compare c-string is strcmp(). + Format Effect strcmp(s1, s2) Returns a value < 0 (-) if s1 less than s2 Returns 0 if s1 and s2 are the same Returns a value > 0 (+) if s1 is greater than s2 Assume that you use the ASCII character set. i. The c-string Air is less than the c-string Boat because the first character of Air is less than the first character of Boat. ii. The c-string Air is less than c-string An because the first character of both string are the same, but the second character i of Air is less than the second character n of An. iii. The c-string Bill is less than the c-string Billy because the first four characters of Bill and Billy are the same, but the fifth character of Bill, which is \0 (the null character), is less than the fifth character of Billy, which is y. iv. The c-string Hello is less than hello because the first character H of the c-string Hello is less than the first character h of the c-string hello. Example #include <string.h> char str1[20], str2[20]; cout << \nenter first string ; cin.getline(str1,20); cout << \nenter second string ; cin.getline(str2,20); if (strcmp(str1, str2) == 0) cout << str1 << and << str2 << are identical ; if (strcmp(str1, str2) > 0) cout << str1 << is greater than << str2; if (strcmp(str1, str2) < 0) cout << str1 << is less than << str2; 14

TUTORIAL 1. What are the TWO (2) values for Boolean expressions? 2. List SIX (6) C++ symbols for relational operators. 3. What is the difference of these operators: = and ==? 4. Give the meaning of the simple Boolean expression. Example: 5 < 10 5 is less than 10. After that evaluate the expression to TRUE or FALSE and write the output of the expression. Boolean Expression Meaning Value Output 9 < 16 8!= 8 3.5 > 6.8 6.9 <= 8.5 5 == 5 5. List THREE (3) C++ symbols for logical operators. 6. What is the difference of these operators: && and? 7. Give the value TRUE or FALSE for the following compound Boolean expressions (NOT). A!A TRUE FALSE 8. Give the value TRUE or FALSE for the following compound Boolean expression (AND and OR): A B A && B A B TRUE TRUE TRUE FALSE FALSE TRUE FALSE FALSE 15

PROBLEM SOLVING AND PROGRAMMING ACTIVITIES 1. Draw a flowchart for a two-way selection structure. 2. Rewrite the following codes into two-way selection structure. a. if (mark >= 50) cout << PASSED << endl; if cout << FAILED << endl; b. if (income <= 1000) tax = income * 0.0125; if (income > 1000) tax = income * 0.0225; incomeaftertax = income tax; c. if (year > 5) rate = 6.5; dividend = investment * rate; balance = investment + dividend; if (year <= 5) rate = 3.5; dividend = investment * rate; balance = investment + dividend; cout << The balance in your account is << balance << endl; d. if (year > 5) rate = 6.5; if (year <= 5) rate = 3.5; dividend = investment * rate; balance = investment + dividend; cout << The balance in your account is << balance << endl; 3. If the payment is between RM5000 to RM10000, display a message that the customer will be given a free air ticket to Langkawi. Otherwise, display a message that the customer will only be given a free lunch at Quality Hotel. Translate the statement above to program segment. 16

4. You are given the following requirements: a. Your program is able to read the amount of sales for a sale executive. b. If the sale is more than RM10,000 then the commission will be 5% of the sale. Otherwise the commission is only 3% of the sales. c. Your program is able to calculate the amount of commission by multiply the percentage of commission with sale. d. Your program is also to display the amount of commission to the sale executive. 5. Draw a flowchart and write a C++ program for a multi-way selection structure to find a maximum value of three integers which are a, b and c. 6. You are given the following requirements: a. Your program is able to read the item code from the keyboard. b. The item code determines the price for each item in the shop. The following table shows the prices and charges of 7 items in the shop. Item Code Price (RM) Charge (%) A 54.00 5 B 65.00 5 C 82.00 5 D 103.00 7 E 150.00 7 F 245.00 10 G 250.00 10 c. If the item code is not matched, an error message is displayed as follows: Error, this item code is not in the list. d. For each selected item, the charge is calculated by multiplying the item price and charge rate. e. Then the payment is a summation of item price and charge. Your program is to display this payment. 17

7. NASA Consultant Co Ltd wants to develop a program that can help the consultant to give advice regarding the home loan. The program receives two inputs from the consultant, which are the amount of House Cost in Ringgit Malaysia and years of term applied. Based on these two inputs, the program should be able to calculate the monthly repayment. The table for the interest calculation is provided as follows: Year of Term Applied Interest (%) More than or equal to 25 years 7.5 More than or equal to 20 years 6.5 More than or equal to 15 years 5.5 More than or equal to 10 years 4.5 Less than 10 years 4.0 The formulae for the monthly repayment calculation are as follows: Interest (RM) = Interest (%) x House Cost (RM) House Cost with Interest = House Cost (RM) + Interest (RM) Monthly Repayment = House Cost with Interest / (Year of Term Applied x 12) 18