Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
If Statements & Relational Operators Programming.
True or false A variable of type char can hold the value 301. ( F )
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
Programming Switch command. COMP102 Prog. Fundamentals: Switch command / Slide 2 Multiple Selection: The switch Statement value1 action 1 value2 action.
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)
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
true (any other value but zero) false (zero) expression Statement 2
1 CS 105 Lecture 4 Selection Statements Wed, Jan 26, 2011, 6:05 pm.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
UNIT II Decision Making And Branching Decision Making And Looping
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Computer Science Department Relational Operators And Decisions.
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.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
Selection Structures (if & switch statements) (CS1123)
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Basic Of Computer Science
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Flow of Control Part 1: Selection
CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how.
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 4 Control Structures I. Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
CPS120: Introduction to Computer Science Decision Making in Programs.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
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.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 3 Control Statements
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Control Structures I (Selection)
CS1100 Computational Engineering
Chapter 7 Conditional Statements
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
Flow of Control.
Presentation transcript:

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming

Outlines 2 if statement Simple Nested Boolean logic switch statement

Outcomes 3 Work out the boolean value of a logic expression Express decision making logic in boolean logic Using if / switch statement to express conditional instructions

Syntax Summary 4 Keywords if, else, switch, case, default, Punctuators (…) {…} : ? : Operators ==, !, !=, >, >=, <, <=, &&, ||

Decision and Action 5 In real-life: We make decisions everyday AC-1 canteen? AC-2? AC-3? Decision will be followed by one or more actions In programming: Decision is based on logical expressions Action is in the form of programming statements

Logical expression and operators 6 Logical expressions can be true or false only x==3 y==x x>10 In C++, any non-zero expression will be treated as logical true 3-2 (true) 1-1(false) x=0(false) x=1(true)

Comparative Operators 7 Binary operators which accept two operands and compare them Relational operatorsSyntaxExample Less than<x<y Greater than>z>1 Less than or equal to<=b<=1 Greater than or equal to>=c>=2 Equality operatorsSyntaxExample Equal to=a==b Not equal to!=!=b!=3

Logical Operators 8 Used for combining logical values and create new logical values Logical AND (&&) return true if both operands are true, false otherwise (e.g., a>1&&b<1) Logical OR (||) return false if both operands are false, true otherwise Logical NOT (!) invert the Boolean value of the operand xyx&&y true false truefalse xyx||y true falsetrue falsetrue false x!x!x truefalse true

Assignment (=) and equality operator (==) 9 Example: x = 1 Assignment operator variable on the left The value of this expression will always equal to the value on the right (1) Example x==1 Equality operator True (evaluates to 1) value of x is 1 False (evaluates to 0) value of x is not 1 No space between the two '='

Relational, equality & logical operators (Summary) 10 q Relational operators less than < greater than > less than or equal to <= greater than or equal to>= q Equality operators equal to == not equal to!= q Logical operators logical not! logical and&& logical or || PS : Expressions with above operators have a true or false value.

Precedence & associativity of popular operators 11 Operator precedence (high to low)Associativity */%*/%Left to right +-+- >=Left to right ==!=Left to right &&Left to right ||Left to right ?:Right to left

Conditional statements 12 In decision making process, logical value can be used to determine the actions to take. E.g. If it is raining, then bring an umbrella If AC1 canteen is too crowded, then go to AC2/AC3 for lunch In programming, certain statements will only be executed when certain condition is fulfilled. We call them conditional statements.

Conditional statement: if 13 One statement will be executed if the condition is true Syntax: if (logical expression) statement; Only one statement will be executed C++ example: cin >>x; if (x<0) x = -x; cout << x << endl; Statement 1 Statement 3 Statement 2 if (logical expression) true

Two-way selection 14 If the condition is true, one statement will be executed. If the condition is false, another statement will be executed. ……………… if (logical expression) //action for true statement a; else //action for false statement b; Statement 1 Statement 3 Statement a if (logical expression) true Statement b false

Some points to note 15 The expression should be enclosed with parenthesis () == No semi-colon after if or else If i==3 is true, then increment a by 1, else i==3 is false, then decrement a by 1. i == 3 evaluates to a non-zero value i == 3 evaluates to zero The else part is optional

Compound statement 16 Group multiple statements into one block using {} to be executed for a certain if, else if, or else statement Must use {} if there’re more than one statements for an if, else, or else if statement if (mark>=90) { cout << “You get grade A.\n"; cout << "Excellent!\n"; }

Compound statement 17 if (j!=3) { b++; cout << b; } else cout < j; if (j!=5 && d==2) { j++; d--; cout << j <<d; } else { j--; d++; cout << j << d; } We may group multiple statements to form a compound statement using a pair of braces {} Compound statements are treated as one statement

Beyond two way condition… 18 Statement 1 Statement 3 Statement a if (logical expression) true Statement b false

Multiple else if statements 19 You can have many nested “else if” statements. if (logical expression 1) //action for true statement a; else if (logical expression 2) //action for true statement b; else //action for false statement; An example: if (score >= 90) grade = ‘A’; else if (score >=75) grade = ‘B’; else if (score >=55) grade = ‘C’; else grade = ‘D’;

Beyond two way condition… 20 In C++, conditional statements have the following format: if (logical expression 1) { statements when expression 1 is true } else if (logical expression 2){ statements when expression 1 is false and expression 2 is true } else if (…){ … } else{ statements when all the logical expressions are false } The else if and else part is optional The curly brackets {} can be omitted if the block contains one statement only.

21 if (logical expression 1) else if (expression 2) else if (expression 3) else

Examples – single statement 22 if (x>5){ cout << “ x is too large’; } if (x>5) cout << “ x is too large”; else if (x<3) cout << “ x is too small”; if (x>5) cout <<“ x is too large”; else if (x<3) cout << “ x is too small”; else cout << “ x is a valid answer”;

Examples – Compound statements 23 if (x==3) cout << “x is equal to 3”; if (x>y){ z=x-y; cout << “x is larger, the difference is ” << z; }else{ z=y-x; cout << “y is larger, the difference is ” << z; }

Beware of empty statements! 24 int x=5; if (x!=5); x=3; cout << x; /*output is 3*/ int x=5; if (x!=5) x=3; cout << x; /*output is 5*/ An empty statement can be specified by a semi-colon ';'. Empty statement specifies that no action should be performed. For program on the right, x=3 statement will NOT be executed if x is equals to 5. For the program on the left, x=3 statement will be always executed.

Nested if statement 25 An if-else statement is included with another if or else statement

26 With which “if” the “else” part is associated? if (a==1) if (b==2) cout << “***\n”; else cout << “###\n”; if (a==1) if (b==2) cout << “***\n”; else cout << “###\n”; Nested if statement

27 An else attached to the nearest if. if (a==1) if (b==2) cout << “***\n”; else cout << “###\n”;

Do not mix == and = 28 Output: “x and y are equal" The expression x = y Assign the value of y to x: x becomes 1 The value of this expression is the value of x (which represents 1/TRUE) False is represented by 0 Non-zero represents TRUE x=0; y=1; if (x = y){ cout << “x and y are equal"; } else cout << "unequal";

Passing CS If you get a total mark greater than or equal to 30. You will pass the course Otherwise, you will fail. Greater than or equal to is a kind of "relational operator" Represented by the operator >= in C++ How to represent the above logic in C++?

Example 1a: Pass or fail? 30 int mark; cout << "What is your mark?\n"; cin >> mark; if (mark>=30) cout << "You passed in CS2311!\n"; The condition should be enclosed within () If the input mark is greater than or equal to 30, the blue statement is executed.

Example 1b: Pass or fail? 31 int mark; cout << "What is your mark?\n"; cin >> mark; if (mark>=30) { cout << "You passed in CS2311!\n"; cout << “congratulations\n”; } If more than 1 statements are specified within an if statement, group the statements in a pair of braces { }

Example 1c: Pass or fail? 32 int mark; cout << "What is your mark?\n"; cin >> mark; if (mark>=30) { cout << "You passed in CS2311!\n"; cout << "Congratulations\n"; } else cout << "You failed in CS2311!\n"; The else statement is executed when the condition mark>=30 is false

Example 1c: Pass or fail? 33 int mark; cout << "What is your mark?\n"; cin >> mark; if (mark>=30) { cout << "You passed in CS2311!\n"; cout << "Congratulations\n"; } else cout << "You failed in CS2311!\n"; cout << "You should retake the course\n"; Suppose the user inputs 31. The output: You passed in CS2311! Congratulations You should retake the course Why?

Example 1c: Pass or fail? 34 int mark; cout << "What is your mark?\n"; cin >> mark; if (mark>=30) { cout << "You passed in CS2311!\n"; cout << "Congratulations\n"; } else { cout << "You failed in CS2311!\n"; cout << "You should retake the course\n"; } Use curly brackets {} to group the statements in the else part

Mark to grade conversion 35

Mark to grade conversion (else-if version) 36 if (mark 100) cout << "Invalid Grade"; else if (mark>=70) cout << "A"; else if (mark>=55) cout << "B"; else if (mark>=45) cout << "C"; else if (mark>=34) cout << "D"; else cout << "F"; The "else if" or "else" part is executed only if all the preceding conditions are false

37 if (mark>=70 && mark<=100) cout << "A"; if (mark>=55 && mark<70) cout << "B"; if (mark>=45 && mark<55) cout << "C"; if (mark>=34 && mark<45) cout << "D"; if (mark 0) cout << "F"; if (mark 100) cout << "Invalid Grade"; if (mark 100) cout << "Invalid Grade"; else if (mark>=70) cout << "A"; else if (mark>=55) cout << "B"; else if (mark>=45) cout << "C"; else if (mark>=34) cout << "D"; else cout << "F";

C++ syntax is different from the math syntax 38 if (mark>=70 && mark<=100) …… Can we express the above condition as follows? if (70<=mark<=100) …… Ans: No

Nested-if 39 An if statement can be nested within another if statement if(mark>=70 && mark <=100) //get an A grade but can be A-, A or A+ { if (mark>90) cout << "You get grade A+.\n"; else if (mark>80) cout << "You get grade A.\n"; else cout << You get grade A-.\n"; } else if …… A- grade is obtained if “mark>=70 and mark<100” and “mark<=80”

Example 2b 40 Modify the program so that if the mark is 100, "Full mark!" will be printed (in addition to the grade). if(mark>=70 && mark <=100) //get an A grade but can be A-, A or A+ { if (mark>90) cout << "You get grade A+.\n"; else if (mark>80) cout << "You get grade A.\n"; else cout << You get grade A-.\n"; } else if ……

The program 41 if (mark>=70 && mark <=100){ if (mark>90) { cout << "You get grade A+.\n"; if (mark==100) cout << "Full mark!\n"; } else if (mark>80) cout << "You get grade A.\n"; else cout << "You get grade A-.\n"; } else if ……

true ? Short-circuit evaluation 42  Evaluation of expressions containing && and || stops as soon as the outcome true or false is known and this is called short- circuit evaluation, x true yx&&y true falsetrue false true false x true yx||y falsetrue false true false true false

Short-circuit evaluation 43  Evaluation of expressions containing && and || stops as soon as the outcome true or false is known and this is called short- circuit evaluation, q E.g., if( 1<0 && y=2 ) is the same as if (false && true), and thus y=2 is not executed! true ? x yx&&y true falsetrue false x true yx||y true false true false true false

Short-circuit evaluation 44  Evaluation of expressions containing && and || stops as soon as the outcome true or false is known and this is called short- circuit evaluation, q E.g., if( 1<0 && y==2 ) is the same as if (false && true/false), and thus …. q Short-circuit evaluation can improve program efficiency q Short-circuit evaluation exists in some other programming languages, e.g., C and Java

Short-circuit evaluation 45 q Given integer variables i, j and k, what are the outputs when running the program below? k = (i=2) && (j=2); cout << i << j << endl; /* 2 2 */ k = (i=0) && (j=3); cout << i << j << endl; /* 0 2 */ k = i || (j=4); cout << i << j << endl; /* 0 4 */ k = (i=2) || (j=5); cout << i << j << endl; /* 2 4 */ ? x true yx&&y true falsetrue false true x yx||y true false true false true false x && y

switch statement: Syntax 46 switch(expression) //similar to if(expression) { case constant-expression: statement(s); break; //optional case constant-expression: statement(s); break; //optional // you can have any number of case statements. default : //Optional statement(s); }

switch statement 47 q Semantics Evaluate the switch expression which results in an integer value ( int, long, short, char )

switch statement: Syntax 48 switch(expression) //e.g., switch(x) { case constant-expression://case 1: statement(s); break; //optional tatement(s); break; //optional // you can have any number of case statements. default : //Optional statement(s); } Go to the case label having a constant value that matches the value of the switch expression; if a match is not found, go to the default label; if default label does not exist, terminate the switch Terminate the switch when a break statement is encountered

switch statement: Syntax 49 switch(expression) //similar to if(expression) { case constant-expression://case 1: statement(s); break; //optional case constant-expression://case 2: statement(s); break; //optional // you can have any number of case statements. default : //Optional statement(s); } If there is no break statement, execution “ falls through ” to the next statement in the succeeding case

Example 50 #include using namespace std; void main(){ int x; cin >> x; switch (x){ case 0: cout << “Zero”; break; /* no braces is needed */ case 1: cout << “One”; break; case 2: cout << “Two”; break; default: cout << “Greater than two”; } //end switch }

Example 51 #include using namespace std; void main(){ int x=0; switch (x){ case 0: cout << “Zero”; x=1; break; /* no braces is needed */ case 1: cout << “One”; break; case 2: cout << “Two”; break; default: cout << “Greater than two”; } //end switch }

conditional ( ?: ) operator 52  Syntax of ?: operator is expr1 ? expr2 : expr3, E.g., (a>b) ? a=1 : a=0 q Semantics expr1 is evaluated If the result is non-zero/true, then execute expr2 ; else expr3 is executed The value of the whole ?: expression is the value of expression evaluated at the end E.g., int min_ x = (x>y) ? y : x; //finds the minimum value of x and y.

Summary 53 Boolean logic has two values only; true or false. Conditional statements are the statements that only execute under certain conditions. In C++, there are two approaches to construct conditional statement if (…){…}else{…} switch(…){…case:break}