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

Similar documents
Decisions. Arizona State University 1

Chapter 4: Making Decisions

Chapter 4: Making Decisions

LECTURE 04 MAKING DECISIONS

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

Lecture 5: Making Decisions

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

5. Selection: If and Switch Controls

Software Design & Programming I

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

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

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

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

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

Chapter 4 - Notes Control Structures I (Selection)

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

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

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Introduction to Programming

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

Add Subtract Multiply Divide

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

CSCE 206: Structured Programming in C++

Logical Operators and if/else statement. If Statement. If/Else (4.3)

CS150 Introduction to Computer Science 1. Logical Operators and if/else statement

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

If Control Construct

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

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

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

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

Unit 7. 'while' Loops

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

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

Decision Control Structure. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

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

Boolean Algebra Boolean Algebra

Topics. Chapter 5. Equality Operators

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

SFU CMPT Topic: Control Statements

Chapter 7. Additional Control Structures

Linear execution of statements. CISC 1600/1610 Computer Science I. Alternatives to linear execution. Linear execution of statements

Flow Control: Branches and loops

Conditional Statement

LECTURE 5 Control Structures Part 2

C++ PROGRAMMING SKILLS Part 2 Programming Structures

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

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

Control Structure: Selection

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

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

Increment and the While. Class 15

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

CS 115 Lecture 8. Selection: the if statement. Neil Moore

C/C++ Programming Lecture 7 Name:

Chapter 3. More Flow of Control

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

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

Looping. Arizona State University 1

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

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

Computational Expression

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

Loops and Files. of do-while loop

UEE1302(1102) F10: Introduction to Computers and Programming

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

Chapter 2. C++ Basics

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

Introduction to C Programming

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

int x = 5; double y = 3; // Integer division rounds the result down to the nearest whole number. cout << "1a: " << x / 3 << endl; //1

CSI33 Data Structures

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

LAB 4.1 Relational Operators and the if Statement

REPETITION CONTROL STRUCTURE LOGO

Score score < score < score < 65 Score < 50

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

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

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Programming Logic and Design Sixth Edition

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

More Complex Versions of the if Statement. Class 13

Boolean Algebra A B A AND B = A*B A B A OR B = A+B

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

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

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

Fundamentals of Programming

1.4 Control Structures: Selection. Department of CSE

Why Is Repetition Needed?

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

Introduction to Programming EC-105. Lecture 2

conditional statements

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

INTRODUCTION TO COMPUTER SCIENCE - LAB

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

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

Logical Operators and switch

Transcription:

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

Learning Outcomes At the end of this lecture, you should be able to: 1. Explain the concept of selection control structure 2. Use relational and logical operators 3. Use if, if..else, if..else if, switch..case, and nested if statements and conditional operators in program. 2

Control Structures Program is written using simple control structures to determine the flow of program execution. Three types of control structure: sequential, selection, repetition. SEQUENTIAL is a series of statements that execute one after another. statement 1 statement 2 statement 3. 3

Control Structures. SELECTION (branch) - is used to execute one set of statements if a given condition is TRUE, a different set of statements, or no statements at all, is executed if the condition is FALSE. statement set 1 condition statement set 2. 4

3. SYSTEM DESIGN continued Control Structures REPETITION (loop) - is used to execute a set of statements repeatedly as long as a given condition is TRUE.. Condition. statement set 5

The logic flow of Control Structures Sequential Selection false? true? : boolean expression Repetition? true false? : boolean expression 6

Why Selection? Selection structure allows the program to select an action (statements to execute), based upon a condition. For example, by using an if statement to check the password entered, your program can decide whether or not a user is allowed access to the program. The condition in this example is a valid password. Condition is evaluated (checked and determined) to be either true or false. 7

Understand TRUE and FALSE The operator will assign 1 if the evaluation is true, or 0 if the evaluation is false. true or false is known as boolean value (bool). An expression (program code that has a value) that has a boolean value is called a boolean expression. Thus, a condition is a boolean expression. 8

Boolean Expression There are a number of operators that allow checks on condition. There are two types of operators that could be used in boolean expression: relational operators and logical operators. Expression with a relational operator is called relational expression, and with logical operator is called logical expression. Relational and logical expressions are both boolean expressions, and can be used as condition. 9

Relational Operators Used to compare between two values. Operator Meaning Relational Result Expression < less than 1 < 2 true < = less than or equal to 1 < = 2 true > greater than 1 > 2 false > = greater than or equal to 1 > = 2 false = = equal to 1 = = 2 false! = not equal to 1! = 2 true 10

Relational Operators More examples: Assume int y=6, x=5; Relational Operators Sample Relational Expression Value > y > x T < y < 2 F > = x > = 3 T < = y < = x F = = x = = 5 T! = y! = 6 F 11

Logical Operators Used to combine two or more relational expressions into one. && AND New relational expression is true if both expressions are true expression1 && expression 2 OR New relational expression is true if either expression is true expression1 expression2! NOT Reverses the value of an expression; true expression becomes false, false expression becomes true! expression 12

Logical Operators Truth table for boolean expression A B A&&B A B!A!B 0 0 0 0 1 1 0 1 0 1 1 0 1 0 0 1 0 1 1 1 1 1 0 0 13

Logical Operator && (AND) Example : Assume int x = 4, y = 5, z = 8; expression1 expression2 expression1 && expression2 Sample Expression F F F ( y > 10) && ( z < =x ) F T F ( z < = y) && ( x = = 4) T F F ( y! = z) && ( z < x ) T T T ( z > = y ) && ( x! = 3) 14

Logical Operator (OR) Example : Assume int x = 4, y = 5, z = 8; expression1 expression2 expression1 expression2 Sample Expression F F F ( y > 10) ( z < = x ) F T T ( z < = y) ( x = = 4) T F T ( y! = z) ( z < x ) T T T ( z > = y ) ( x! = 3 ) 15

Logical Operator! (NOT) Example : Assume int x = 50 expression! expression Sample Expression F T! (x = = 60) T F! (x! = 60) 16

Precedence of Logical Operator Highest! && Lowest Example: (2 < 3) (5 > 6) && (7 > 8) 2 is true because AND is evaluated before OR 1 17

More on Operator Precedence Example: Highest Lowest Arithmetic operators Relational operators Logical operators 8 < 2 + 7 5 == 6 is true 1 2 3 4 16

Boolean Expressions Can be assigned to a variable Example : bool result = (x <= y); bool flag = true; Assigns 0 for false, 1 for true Do not get confused between: = (assignment) and == (equal to) 19

Checking Numeric Ranges with Boolean Operators Used to test if a value is within a range if (grade >= 0 && grade <= 100) cout << "Valid grade"; Can also test if a value lies outside a range if (grade < 0 grade > 100) cout << "Invalid grade"; Cannot use mathematical notation if (0 <= grade <= 100) //Doesn t //work! 20

Notes on expression An arithmetic expression that evaluates to a nonzero number is a true boolean expression. An arithmetic expression that evaluates to zero is a false boolean expression. 21

Selection Control Structure Single way Two way : using if statement : using if else statement, or using conditional operator Multiple way : using if else if statement, or using switch case statement Nested if 22

The if Statement Use to code a single way selection structure Allows statements to be conditionally executed, or skipped over Models the way we mentally evaluate situations. Example: If it is cold outside, wear a coat and wear a hat. 23 4-23

Structure of if statement NO ; after condition if (condition) { statement_1; statement_2; statement_n; } condition true 1 or more statements false If (condition) is true, then the statement(s) in the body are executed. If (condition) is false, then the statement(s) are skipped. The block of statements within the { } is called the body of the if statement. If 24 there is only ONE statement in the body, the { } may be omitted.

Things to REMEMBER about if Statement DO NOT place ; after (condition) Don't forget the { } around a multistatement body Place each statement on a separate line after (condition), and indent it. (condition) : 0 means false; any other value means true 25 4-25

Example of if statement Example : To calculate and print the value of a. If a<10, then a is multiplied with b. false Start Read a a<10 Print a Stop true a =a*b int main() { } int a, b = 5; cin >> a; if (a < 10) a = a * b; cout<<a; return 0; 26

More Example: if Statement if (score >= 60) cout << "You passed.\n"; if (score >= 90) { grade = 'A'; cout << "Wonderful job!\n"; } REMEMBER : If there are > 1 statements in the body, MUST use { } 27 4-27

More Example: if Statement Look at the use of condition in if statement: bool validmonths; int months; double numofpayment,total; cin >> months >> total; if (months < 0) validmonths = false; if (validmonths) numofpayment = total / months; 28 4-28

The if..else Statement Use to code a two way selection structure Allows a choice of execution between statements depending on whether (condition) is true or false Models the way we mentally evaluate situations Example : If it is raining, take an umbrella, else, take a hat. 29 4-29

Structure of if else statement if (condition) { statement set 1; } else { statement set 2; } true statement set 1 condition false statement set 2 If (condition) is true, statement set 1 is executed and statement set 2 is skipped. If (condition) is false, statement set 1 is skipped and statement set 2 is executed. 30

Example of if else statements Example: To determine odd or even number Start int main() { false Read a a%2==0 true Print a, is an odd number Print a, is an even number int a; cin >> a; if (a % 2 = = 0) cout<< a << is an even number ; else cout << a << is an odd number ; Stop } return 0; 31

More Example: if..else Statements if (score >= 60) cout << "You passed.\n"; else cout << "You did not pass.\n"; if (intrate > 0) { interest = loanamt * intrate; cout << interest; } else cout << "You owe no interest.\n"; 32 4-32

Example of if else statements discount = 0; if (price<100); else discount = price *0.3 ; same as discount = 0; if (!(price<100)) discount = price *0.3 ; else ; same as discount = 0; if (!(price<100)) discount = price *0.3 ; 33

Example of if else statements (with errors!) if (score<40) cout<< Failed ; cout<< Work Harder ; else cout<< Passed ; cout<< Congratulations ; same as if (score<40) cout<< Failed ; cout<< Work Harder ; else Notes : error! else without matching if cout<< Passed ; cout<< Congratulations ; 34

The Conditional Operator Can use to create short if/else statements Format: expr? expr : expr; x<0? y=10 : z=20; First Expression: Expression to be tested 2nd Expression: Executes if first expression is true 3rd Expression: Executes if the first expression is false 35

The Conditional Operator The value of a conditional expression is The value of the second expression if the first expression is true The value of the third expression if the first expression is false Parentheses () may be needed in an expression due to precedence of boolean operator 36

Program example: Conditional Operator 37

The if..else if Statement Use to code a multiple way selection structure Chain of if statements that a condition is tested in order until one condition is found to be true Also models thought processes Example : If it is raining, take an umbrella, else, if it is windy, take a hat, else, if it is sunny, take sunglasses. 38 4-38

Structure of if else if statement if(condition1) { statement set 1 } else if(condition2) { statement set 2 } else if(condition3) { statement set 3 } else statement set4 condition1 f condition2 f condition3 f Statement set 4 t t t Statement set 1 Statement set 2 Statement set 3 39

From the previous slide If (condition1) is true, statement set 1 is executed and the rest of the statement sets are skipped. But If (condition1) is false, statement set 1 is skipped. Next check on (condition2). If (condition2) is true, statement set 2 is executed and the rest of the statement sets are skipped. But If (condition2) is false, statement set 2 is skipped. Next check on (condition3). If (condition3) is true, statement set 3 is executed and the rest of the statement sets are skipped. But If (condition3) is false, statement set 3 is skipped. Statement set 4 is executed. 40

Example of multiple way selection (using if..else if statement) Example: To determine and print a student s grade from the test mark. Start Read student s test mark; mark mark >=90 && mark <= 100 true Print Grade A false mark >=80 && mark < 90 true Print Grade B false 1 2 41

1 2 mark >= 70 && mark <80 true Print Grade C false mark >= 60 && mark < 70 false mark >= 0 && mark <60 false Print Not a valid input true true Print Grade D Print Grade F Stop 42

int main( ) { int mark; char Grade; cout << Please enter the test mark for a student : ; cin >> mark; if (mark >=90 && mark <= 100) cout << Gred A ; else if (mark >=80 && mark < 90) cout << Gred B ; else if (mark >= 70 && mark <80) cout << Gred C ; else if (mark >= 60 && mark < 70) cout << Gred D ; else if (mark >= 0 && mark <60) cout << Gred F ; else cout << Not a valid input. ; } 43

More Example : if..else if if (age >= 21) cout << "Adult"; else if (age >= 13) cout << "Teen"; else if (age >= 2) cout << "Child"; else cout << "Baby"; 44 4-44

Multiple way selection using switch..case statement must be either bool value, integer types, or a character 45

Structure of Multiple way selection using switch..case statement 46

47

switch (mark/10) { case 10 : case 9 : grade = A ; break; case 8 : grade = B ; break; case 7 : grade = C ; break; case 6 : grade = D ; break; Example of switch case 5 : case 4 : case 3 : case 2 : case 1 : case 0 : grade = F ; break; default : } 48

switch (selection) Example of switch { case 'A' : cout << "\n To append a record" << endl; break; case 'M' : cout << "\n To modify a record" << endl; break; case 'D' : cout << "\n To delete a record" << endl; break; case 'X' : cout << "\n To exit the menu" << endl; break; default : cout << "\n Invalid selection" << endl; } 49

Menu-Driven Program Menu: list of choices presented to the user on the computer screen Menu-driven program: program execution controlled by user selecting from a list of actions Menu can be implemented using if..else if or switch..case statements 50 4-50

Menu-driven Program Organization Display list of numbered or lettered choices for actions. Input user s selection of number or letter Test user selection in (condition) If match, then execute code to carry out desired action if not, then test with next (condition) 51 4-51

Nested if Statements Is an if statement that is part of the if or else part of another if statement Can be used to evaluate more then 1 conditions. Example : To set the grade to A, score is between 90 and 100 if (score < 100) { // The second if is a nested if that resides in the if part of the first if. if (score > 90) grade = 'A'; } 52 4-52

Notes on Coding Nested ifs An else matches the nearest if that does not have an else if (score < 100) if (score > 90) grade = 'A'; else... // goes with second if, // not first one Proper indentation helps you to understand the codes. 53 4-53

Nested if statement false true false true 54

if (job_title == 'a') // a = associate professor if (year_served > 5) if (no_of_publications > 7) cout << "\npromote to Professor" endl; else cout << "\nmore publications required" << endl; else cout << "\nmore service required" << endl; else cout << "\nmust become associate professor first" << endl; Example of nested if code 55

Dangling else in nested if statement false true false true 56

Example of dangling else in nested if if (score>40) if (mark==100) cout << "\nfull mark. Congratulations." << endl; else cout << "\nfailed. Must work harder" << endl; SAME AS if (score>40) { if (mark==100) cout << "\nfull mark. Congratulations." << endl; else cout << "\nfailed. Must work harder" << endl; } 57

Solution of dangling else in nested if statement Dangling else solution 58

Example: Solution of dangling else in nested if if (score>40) { } else if (mark==100) cout << "\nfull mark. Congratulations." << endl; cout << "\nfailed.must work harder" << endl; - THE END - 59