Computer Science, City University of
Semester B 2021-22
CS2310 Computer Programming
Copyright By PowCoder代写 加微信 powcoder
LT4: Control Flow – Conditional Statements
Sequential Flow of Control
So far, the control flow is completely sequential
Program always executes the same sequence of statements from the start of the program to the end
In some situations, we want to our program to produce different effects based on different program conditions
In other words, we want our code to produce different sequences of statements
Decision and Action
We make decisions everyday
AC-1 canteen? AC-2? AC-3?
Decision will be followed by one or more action(s)
In programming:
Decision is based on conditions, e.g., logical expressions
Action is in the form of programming statements
Comparative Operators
Binary operators which accept two operands and compare them
Relational operators Syntax Example
Less than < x
Less than or equal to <= b<=1
Greater than or equal to >= c>=2
Equality operators Syntax Example
Equal to == a==b
Not equal to != b!=3
Logical expression and operators
Logical expressions can be true or false only
In C++, any non-zero expression will be treated as logical true
Assignment (=) and equality operator (==)
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 ‘=’
Logical Operators
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)
Example: 18 < age < 60 should be written as: 18 < age && age < 60;
Logical OR (||)
return false if both operands are false, true otherwise
Logical NOT (!)
invert the Boolean value of the operand
true true true
true false false
false true false
false false false
true true true
true false true
false true true
false false false
true false
false true
The Logical-NOT Operator
Logical-NOT (!) is a unary operator (it only takes one operand). So how does it work?
To check if age is not between 18 and 65, we simply write:
!(age >= 18 && age <= 65)
The Logical-NOT operator only takes one operand, evaluates the operand to true or false, then flips the result
Effect of Logical-Not Operator
Original Expression Equivalent Expression
!(x
!(x>y) x<=y
!(x!=y) x==y
!(x<=y) x>y
!(x>=y) x
less than or equal to <=
greater than or equal to >=
Equality operators
equal to ==
not equal to !=
Logical operators
logical not !
logical and &&
logical or ||
PS: Expressions with above operators have a true or false value.
Precedence & associativity of popular operators
Operator precedence (high to low) Associativity
* / % Left to right
+ – Left to right
< <= > >= Left to right
== != Left to right
&& Left to right
|| Left to right
?: Right to left
Conditional statements
In decision making process, logical value can be used to determine the actions to take.
If AC2 canteen is too crowded, then go to AC1/AC3 for lunch
In programming, certain statements will only be executed when certain condition is fulfilled. We call them conditional statements
Conditional statement: if
One statement will be executed if the condition is true
if (logical expression)
statement;
Only one statement will be executed
“If (logical expression) statement” is one statement in C++.
C++ example:
cout << x << endl;
Statement 1
Statement 3
Statement 2
if (logical expression)
Two-way selection
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;
//action for false
statement b;
Statement 1
Statement 3
Statement a
if (logical expression)
Statement b
Some points to note
The expression should be enclosed with parenthesis ()
No semi-colon after if or else
The else part is optional
Compound statement
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 (conditional expression)
statementstrue ...
“If (condition) {statement; statement; ...}” is one statement
if (mark>=90)
cout << “You get grade A.\n";
cout << "Excellent!\n";
Compound statement
cout << b;
if (j!=5 && d==2)
cout << j <
grade = ‘A’;
else if (score >=75)
grade = ‘B’;
else if (score >=55)
grade = ‘C’;
grade = ‘D’;
Mark to grade conversion
Mark to grade conversion
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<34 && mark>0)
cout << "F";
if (mark<0 || mark>100)
cout << "Invalid Grade";
if (mark<0 || 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";
cout << "F";
Beyond two way condition…
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 (…){
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.
Beware of empty statements!
if (x!=5);
cout << x;
/*output is 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
An if-else statement is included with another if or else statement
With which “if” the “else” part is associated?
cout << “***\n”;
cout << “###\n”;
cout << “***\n”;
cout << “###\n”;
Nested if statement
An else attached to the nearest if.
cout << “***\n”;
cout << “###\n”;
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";
cout << You get grade A-.\n";
else if ……
Example 2b
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";
cout << You get grade A-.\n";
else if ……
The program
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";
cout << "You get grade A-.\n";
else if ……
Do not mix == and =
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
if (x = y){
cout << “x and y are equal";
cout << "unequal";
C++ syntax is different from the math syntax
if (mark>=70 && mark<=100)
Can we express the above condition as follows?
if (70<=mark<=100)
E.g.: check if a year is a leap year
E.g.: check if a year is a leap year
Short-circuit evaluation
Evaluation of expressions containing && and || stops as soon as the outcome true or false is known and this is called short-circuit evaluation
Short-circuit evaluation
Evaluation of expressions containing && and || stops as soon as the outcome true or false is known and this is called short-circuit evaluation,
E.g., if( 1<0 && y=2 ) is the same as if (false && true), and thus y=2 is not executed!
Short-circuit evaluation
Evaluation of expressions containing && and || stops as soon as the outcome true or false is known and this is called short-circuit evaluation,
E.g., if( 1<0 && y==2 ) is the same as if (false && true/false), and thus ….
Short-circuit evaluation can improve program efficiency
Short-circuit evaluation exists in some other programming languages, e.g., C and Java
Short-circuit evaluation
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 && y
switch statement: Syntax
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
Syntax (selection statement)
switch (expression) {
case constant-expr1: statement1
case constant-expr2: statement2
case constant-exprN: statementN
default: statement
switch statement: Syntax
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
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
#include
using namespace std;
void main(){
switch (x){
cout << “Zero”;
break; /* no braces is needed */
cout << “One”;
cout << “Two”;
cout << “Greater than two”;
} //end switch
#include
using namespace std;
void main(){
switch (x){
cout << “Zero”;
break; /* no braces is needed */
cout << “One”;
cout << “Two”;
cout << “Greater than two”;
} //end switch
switch statement
Evaluate the switch expression which results in an integer type (int, long, short, char)
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
If there is no break statement, execution “falls through” to the next statement in the successful case
conditional (?:) operator
Syntax of ?: operator is
expr1 ? expr2 : expr3
E.g., (a>b) ? a=1 : a=0
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., finds the maximum value of x and y
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}
Statement 2a
Statement 3
Statement 1
Statement 2c
Statement 2b
Logical Expresson
Statement 2a
Statement 3
Statement 1
Statement 2c
Logical Expresson
Statement 2b
mark<0 || mark Invalid Grade mark<0 || mark >100
Invalid Grade
Statement 1
expression1
Statement 2a
expression2
Statement 3
Statement 2b
if (expression1)
if (expression2)
statement2a
statement2b
statement3
statement1
Statement 1
expression1
Statement 2a
expression2
Statement 3
Statement 2b
if (expression1)
if (expression2)
statement2a
statement3
statement2b
statement1
cout << “***\n”; cout <<“###\n”; cout << “***\n”; cout <<“###\n”; cin >> yearyear % 4 == 0leap = 1trueyear % 100 == 0cout << leaptrueleap = 1falseyear % 400 == 0truefalseleap = 0leap = 0false cin >> year
year % 4 == 0
year % 100
cout << leap year % 400 /docProps/thumbnail.jpeg 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com