0% found this document useful (0 votes)
26 views42 pages

C++ Conditional Execution Guide

The document provides an overview of conditional execution and branching in C++, detailing how to use conditional statements like 'if', 'else', and 'else if'. It explains the syntax, common mistakes, and the importance of using compound statements for multiple actions. Additionally, it covers logical and comparison operators, operator precedence, and the concept of short-circuit evaluation.

Uploaded by

123456789hoikin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views42 pages

C++ Conditional Execution Guide

The document provides an overview of conditional execution and branching in C++, detailing how to use conditional statements like 'if', 'else', and 'else if'. It explains the syntax, common mistakes, and the importance of using compound statements for multiple actions. Additionally, it covers logical and comparison operators, operator precedence, and the concept of short-circuit evaluation.

Uploaded by

123456789hoikin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Programming

Conditional Execution / Branching


Conditional statements
So far, all statements we wrote in a C++ program run in sequence
We can actually ask the program to run (or not to run) a statement
by considering some conditions / criteria set by us.
It is called "conditional execution" or "branching"
Syntax:
if (<condition>) <statement>;

<statement> will be executed only when the <condition> is fulfilled


(i.e. is true) otherwise, the statement is skipped as if it does not exist
at all

2
Conditional statement: Simplest form - if
One or more statements will be executed if the condition is true

………………
if ( logical value / expression)
action for logical value true

………………

C++ example:

cin >>x;
if (x<0)
x=-x;

cout << "Absolute value is " <<x << endl;


3
Example: Pass or fail?
If the total mark is 35 or above. It is considered "pass".
Otherwise, it is "fail"
How to represent the above logic in C++?
int mark;
cout << "What is your mark?\n";
cin >> mark;
if ( mark>=35 )
cout << "You passed!\n";

Note: The condition MUST be enclosed within ( )

If the input mark is greater than or equal to 35,


the blue statement is executed.
4
Two-way selection
If the condition is true, one ore more statements will be executed. If
the condition is false, another set of statement will be executed.

………………
if ( Logical expression)
statement2a //action for true
else
statement2b //action for false

………………

C++ example:

if (x>=0)
cout << "Positive ";
else
cout << "Negative ";
5
Some points to note
The expression MUST be
enclosed by ( ) No semi-colon after if
It is NOT optional! or else

==

The else part is


optional

i == 3 evaluates to a
Boolean value

If i==3 is true, increment a by 1, otherwise (i==3 is false),


6 decrement a by 1
Beware of the semi-colon!
int x=5; int x=5;
if (x!=5); if (x!=5)
x=3; x=3;
cout << x; cout << x;
/*output is 3*/ /*output is 5*/

An empty statement can be specified by a semi-colon ';'. Empty statement


specifies that no action should be performed. You may consider it as empty { }

For the second program, x is assigned 3 when x is not equals to 5. (Correct!)

For the first program, because of the extra semi-colon at the end of the if
statement, nothing is executed when x!=5.
Meanwhile x=3 is not attached to if and it ALWAYS execute.
7
Compound statement
Group statements into an executable block with { }
It is needed if we want to execute two or more statements
following the if clause.
All-or-Nothing: Either all executed or all skipped
Used for if, else if, and else statement, as well as loops
which we’ll go through in the next lecture
if (mark>=70){
cout << "You get grade A.\n";
cout << "Excellent!\n";
}
 Suggestion: Always use { } even if there’s only one (or zero)
statement. It would be easier for future debugging.
8
Examples – Compound statements

if (x==3)
Compound statements {…}
cout << "x is equal to 3"; are treated as one statement

if (x>y){
z=x-y;
cout << "x is larger, the different is " << z;
}else{
z=y-x;
cout << "y is larger, the different is " << z;
}

9
Pass or fail? -- Common Mistake
int mark;
cout << "What is your mark?\n";
cin >> mark;
if (mark>=35){
cout << "You passed!\n";
cout << "Congratulations\n";
}
else
cout << "You failed!\n";
cout << "You should retake the course\n";

Suppose the user inputs 35. The output:


You passed!
Congratulations
You should retake the course

Why?
10
Pass or fail? – Corrected Program
int mark;
cout << "What is your mark?\n";
cin >> mark;
if (mark>=35){
cout << "You passed!\n";
cout << "Congratulations\n";
}
else {
cout << "You failed!\n";
cout << "You should retake the course\n";
}

Similar to if, else controls just ONE statement.


If >1 statements are needed in the else part, let’s
group the statements with brackets

11
Beyond two way condition…

12
Beyond two way condition…
If you’d like to further sub-divide the "false" part, you may use the
else if () statement, by providing another condition to check
else if is considered only when the previous if () clause is false

if ( logical value 1) {
statements for logical value is true
}else if (logical value 2){
statements for logical value 1 is false but logical value 2 is true
}else if (…) {

}else{
statements for all the logical values are false
}

13
Statement 1

false true
Logical
Expresson

Logical
Statement 2a
Expresson

Logical Statement 2b
Expresson

Statement 2d Statement 2c

Statement 3

14
Examples

if (x>5){ if (x>5)
cout << " x is too large"; cout <<" x is too large";
} else if (x<3)
cout << " x is too small";
else
cout << " x is in range 3..5";

if (x>5)
cout << " x is too large";
else if (x<3)
cout << " x is too small";

15
Nested if statement
"Nested" means enclosing an if statement inside another if statement

statement1

if (expression1)
if (expression2)
statement2a

else
statement2b

statement3

16
Dangling else problem
With which "if" the "else" part is associated?

if (a==1) if (a==1)
if (b==2) if (b==2)
cout << "***\n"; cout << "***\n";
else else
cout << "###\n"; cout << "###\n";

Actually the 2 pieces of code here are identical

17
Dangling else problem
C++ ignores spacing and indentation
An else is ALWAYS attached to the nearest if.
if (a==1)
if (b==2)
cout << "***\n";
else
cout << "###\n";

18
Condition
The "condition" in brackets is usually an expression,
which evaluates to Boolean true or false (e.g. if (a>5) …. )
It can also be a Boolean variable
(e.g. bool found=true; if ( found ) …. )
It can actually be an integer as well (rarely used!)
(e.g. int x=5; if ( x ) …. )
Integer value zero is considered false
All other integer values (e.g. 1, -1…etc.) are considered true
So if (x) …. actually means if (x!=0) …..

19
Comparative Operators
Binary operators which accepts two operands and
compare them

Relational operators Syntax Example


Less than < x<y
Greater than > z>1
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

20 No space between the 2 ‘=’s !


Do not mix == (equality) and = (assign)
Common Mistake:
x=0;
y=1;
if (x = y){
cout << "x and y are equal";
}
else
cout << "unequal";

Output: "x and y are equal" (and x changed to 1 as a side-effect)


The expression x = y
• Assign the value of y to x (x becomes 1)
• The value of this expression is the value of x, i.e. 1 (which represent true)
• false is represented by 0
• Non-zero represents true

21
Logical Operators
Used for combining logical values and create new logical values
Logical AND (&&)
return true if both operands are true, false otherwise
Logical OR (||)
return true if at least one side is true, false otherwise
Logical NOT (!)
Invert the Boolean value of the operand

Don’t write | and &, compiler will not spot that mistake for you!
(| and & has a totally different meaning (not taught in this course) It is not syntax error)

22
The NOT (!) operator:
Be aware of the "equals" case when negating relational expressions:
E.g. Opposite of "greater" (>) is not "smaller" (<), but rather it is
"smaller or equals" (<=)

Original Expression Equivalent to:


!(x<y) x>=y
!(x>y) x<=y
!(x!=y) x= =y
!(x<=y) x>y
!(x>=y) x<y
!(x= =y) x!=y

23
The NOT (!) operator:
Also note that negating an expression means:
Negating all sub-expression in it, as well as….
Changing all AND to OR and vice versa

That means: !(a && b) gives (!a || !b) but not (!a && !b)
For example, consider the criteria of passing a course…
First, we need condition a: Exam >= 30
Also we need condition b: Total >= 35
We can write "passing a course" as fulfilling a AND b, i.e. (a && b)
Then we consider the "fail" situation, i.e. !(a && b)…
Fail case happens when a student cannot get 30 in exam (i.e. !a),
OR the total is not 35 or above (i.e. !b)
Again it turns out that !(a && b) is equivalent to (!a || !b)
24
This is known as De Morgan’s Law
Comparing Characters
Besides numbers we can also compare characters
(e.g. ‘A’ < ‘Z’ is true)
Characters are compared using their ASCII code
Therefore ‘A’ (ASCII 65) is smaller than ‘a’ (ASCII 97)
Not that we cannot compare strings / array directly
(e.g. "ABC" < "DEF", or "A"<"D" are SYNTAX ERROR !)
Example: Check whether x is uppercase / lowercase:

If (x>=‘A’ && x<=‘Z’)


cout<<"Uppercase\n";
else if (x>=‘a’ && x<=‘z’)
cout<<"Lowercase\n";
else
cout<<"Not alphabet\n";
Mark to grade conversion (if version)
(less efficient)

if (mark>=70 && mark<=100)


cout << "A";
if (mark>=55 && mark<70)
cout << "B";
if (mark>=40 && mark<55)
cout << "C";
if (mark>=35 && mark<40)
cout << "D";
if (mark<35 && mark>=0)
cout << "F";
if (mark<0 || mark>100)
cout << "Invalid Grade";

26
Mark to grade conversion (else-if version)
(more efficient)

if (mark<0 || mark>100)
cout << "Invalid Grade";
else if (mark>=70)
cout << "A";
else if (mark>=55)
cout << "B";
else if (mark>=40)
cout << "C";
else if (mark>=35)
cout << "D";
else
cout << "F";

The "else if" or "else" part is executed


only if all the preceding conditions are false
27
Mark to grade conversion

28
Common Mistakes: C++ syntax v.s. math syntax

if (mark>=70 && mark<=100)


……
Can we express the above condition as follows?
if (70<=mark<=100)
……
Ans: NO, although the above statement is compilable (no
syntax error), but the meaning / logic is NOT CORRECT!

Similarly, statements like if(a==b==c) is also WRONG!


29
Common Mistakes
WRONG! Correct

if (a=b) if (a==b)

if (a==b==c) if (a==b && b==c)

if (a>b>c) if (a>b && b>c)

if (a>b,c) if (a>b && a>c)

if (a=>b) if (a>=b)

if a>b if (a>b)

30
Summary: Logical/Comparison operators
 Relational operators
less than <
greater than >
less than or equal to <=
greater than or equal to >=
 Equality operators
equal to ==
not equal to !=
 Logical operators
(unary) negation (i.e., not) !
logical and &&
logical or ||

31
Summary: Precedence of operators
Operator precedence (high to low) Associativity
() ++(postfix) – (postfix) Left to right
+(unary) -(unary) ++(prefix)-- (prefix) Right to left
* / % Left to right
+ - Left to right
< <= > >= Left to right
== != Left to right
&& Left to right
|| Left to right
?: Right to left
= += -= *= /= Right to left
,(comma operator) Left to right
32
Do you know: Precedence of && and ||
By default, expressions are evaluated from left to right. Yet things get
complicated since the precedence of && is higher than that of || :
Example: A || B && C means ?
Possibility 1 – expression is true when:
Either A or B is true, and
C has to be true as well (i.e. (A||B) && C )
Possibility 2 – expression is true when:
A is true, or
B and C are true at the same time (i.e. A|| (B && C) )
The Answer is 2. B && C, which are connected with && are considered
together. (Just like A+B*C, B*C are considered together)
The morale of the story is: Let’s use parenthesis if you’re not 100% sure!
Partial (short-circuit) evaluation
 Evaluation of expressions containing && and || stops as soon as
the outcome true or false is known and this is called partial (short-
circuit) evaluation
 For the case of ||, evaluation stops once a sub-expression is true
(e.g. if (x==1||y==3)… Once x is known to be 1, y is not checked)
 For the case of &&, evaluation stops once a sub-expression is false
(e.g. if (x!=0 && y>10)… Once x is known to be 0, y is not checked)
 Short-circuit evaluation can improve program efficiency
 It can possibly avoid error situation as well
(e.g. if ( b>0 && a/b>5) … skipping a/b avoids "division by zero")

34
Advanced Example: Short-circuit evaluation
Let’s try with Visual Studio!
 What are the outputs of the following program?


k = (i=2)√ && (j=2);
cout << i <<" "<< j << endl; //2 2
Be careful,
It’s = but not ==
×
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);
35
cout << i <<" "<< j << endl; //2 4
switch statement
 General format of switch statement (selection statement)

switch (expression) {
case constant-expr1: statement1
case constant-expr2: statement2
...
...
case constant-exprN: statementN
default: statement
}

36
switch statement (cont’d)

 Semantics
Evaluate the switch expression which result in an integer type
(e.g. double a=3.14; switch(a){…} is WRONG!)
(Trying to apply switch to String (multiple characters) is also WRONG!)
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 succeeding case

37
Example: Print English name of numbers

Assume input is in range 1..6 break; is needed after the statement


//assume num is 4; (cout), otherwise the program "falls
through" and also prints "Two","Three"
switch( num ) { ….etc.
case 1: cout<<"One"; break;
case 2: cout<<"Two"; break;
The order of the cases doesn’t matter
case 3: cout<<"Three"; break; (if there’s no "fall through")
case 4: cout<<"Four"; break;
Besides numbers (case 1, case 2…), can
case 5: cout<<"Five"; break; also be characters (case ‘A’, case ‘B’..etc)

case 6: cout<<"Six"; break;


default: cout<<"Error, not 1..6"; break;
}
default is for cases not qualified for any case above
38 (default is optional)
Example: Print Odd/Even (no fall through)
Assume input is in range 1..6

//assume num is 4;
switch( num ) {
case 1: cout<<"Odd"; break;
case 2: cout<<"Even"; break;
case 3: cout<<"Odd"; break;
case 4: cout<<"Even"; break;
case 5: cout<<"Odd"; break;
case 6: cout<<"Even"; break;
default: cout<<"Error, not 1..6"; break;
}
Example: Print Odd/Even (use fall through)
Assume input is in range 1..6

//assume num is 4;
switch( num ) {
case 1:
case 3:
case 5: cout<<"Odd"; break;

case 2: "falls through", as there’s no break in case 4


case 4:
case 6: cout<<"Even"; break;

default: cout<<"Error, not 1..6"; break;


}
Talk like an Alien from the C++ planet…
conditional (?:) operator
 General format of ?: operator is
expr1 ? expr2 : expr3;

 Semantics
Boolean expression expr1 is evaluated
If the result is true, then expr2 is taken as result, otherwise
expr3 is taken as result.

Example:
Find Minimum of x and y: min = (x>y) ? y : x;
(actually it’s identical to: if (x>y) min=y; else min=x; )

Find absolute value of x: value = (x>0) ? x : -x;


(actually it’s identical to: if (x>0) value=x; else value=-x; )
41
Checklist
After this lecture, students are expected to be able to:
Make use of if, else and else if for specifying conditions
Make use of compound statements enclosed by {….}
Write Boolean expressions with operators like == != > < …etc.
Join multiple expressions with AND &&, OR || and NOT !
Explain the concept of partial evaluation in if() statements
Make use of switch() statements for decisions with >2 cases
Explain the need of break; in switch() and the concept of “fall
through”
Rewrite logical statements from one form to another
(e.g. use if-else to replace switch, use nested if to replace if-else)

42

You might also like