0% found this document useful (0 votes)
2 views

lec 5

This document covers conditional statements in programming, focusing on Boolean algebra, logical operators, and control constructs such as if statements and switch statements. It explains the syntax and semantics of these constructs, including examples for clarity. Additionally, it discusses operator precedence and the importance of using break statements in switch cases to prevent fall-through behavior.

Uploaded by

Muhammed
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)
2 views

lec 5

This document covers conditional statements in programming, focusing on Boolean algebra, logical operators, and control constructs such as if statements and switch statements. It explains the syntax and semantics of these constructs, including examples for clarity. Additionally, it discusses operator precedence and the importance of using break statements in switch cases to prevent fall-through behavior.

Uploaded by

Muhammed
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
You are on page 1/ 57

Programming and

Algorithms CSE308
LECTURE 5: CONDITIONAL
STATEMENT
By: Dr. Mostafa Abdelrazik
If Control Construct
A mechanism for deciding whether
an action should be taken

2
Boolean Algebra
Logical expressions have the one of two values - true
or false
A rectangle has three sides
The instructor has a pleasant smile
The branch of mathematics is called Boolean algebra
Developed by the British mathematician George
Boole in the 19th century

Three key logical operators


And
Or
Not
Boolean Algebra
Truth tables
Lists all combinations of operand values
and the result of the operation for each
combination

Example P Q P and Q

False False False


False True False
True False False
True True True
Boolean Algebra

Or truth table
P Q P or Q

False False False


False True True
True False True
True True True
Boolean Algebra

Not truth table


P not P

False True
True False
Boolean Algebra
Can create complex logical expressions
by combining simple logical expressions
Example
not (P and Q)

A truth table can be used to determine


when a logical expression is true
P Q P and Q not (P and Q)
False False False True
False True False True
True False False True
True True True False
A Boolean Type
C++ contains a type named bool
Type bool has two symbolic constants
true
false
Boolean operators
The and operator is &&
The or operator is ||
The not operator is !
Warning
& and | are also operators so be careful what you
type
A Boolean Type

Example logical expressions

bool P = true;
bool Q = false;
bool R = true;
bool S = (P && Q);
bool T = ((!Q) || R);
bool U = !(R && (!Q));
Relational Operators

Equality operators
==
!=

Examples
int i = 32;
int k = 45;
bool q = (i == k);
bool r = (i != k);
Relational Operators
Ordering operators
<
>
>=
<=

Examples
int i = 5;
int k = 12;
bool p = (i < 10);
bool q = (k > i);
bool r = (i >= k);
bool s = (k <= 12);
Operator Precedence Revisited
Precedence of operators (from highest
to lowest)
◼ Parentheses
◼ Unary operators
◼ Multiplicative operators
◼ Additive operators
◼ Relational ordering
◼ Relational equality
◼ Logical and
◼ Logical or
◼ Assignment
Operator Precedence Revisited

Consider
5 * 15 + 4 == 13 && 12 < 19
|| !false == 5 < 24
Operator Precedence Revisited

Consider
5 * 15 + 4 == 13 && 12 < 19
|| !false == 5 < 24

Yuck! Do not write expressions like this!


Operator Precedence Revisited
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

 However, for your information it is equivalent to


((((5 *15) + 4) == 13) && (12 < 19))
||
((!false) == (5 < 24))
Conditional Constructs
Provide
Ability to control whether a statement list is
executed

Two constructs
If statement
– if
– if-else
– if-else-if

Switch statement
– Left for reading
The Basic If Statement
Syntax
if (Expression)
Action Expression

If the Expression is true true false


then execute Action

Action
Action is either a single
statement or a group of
statements within braces
Example
if (Value < 0) {
Value = -Value; Is our number negative?

}
If Value is less than Value < 0
zero then we need to
update its value to
true false
that of its additive
inverse If Value is not less
than zero then our
Value = -Value number is fine as is

Our number is
now definitely
nonnegative
Sorting Two Numbers
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
if (Value1 > Value2) {
int RememberValue1 = Value1;
Value1 = Value2;
Value2 = RememberValue1;
}
cout << "The input in sorted order: "
<< Value1 << " " << Value2 << endl;
Semantics
Are the numbers
out of order
Rearrange value1
and value2 to value2 < value1
put their values
in the proper
order true false

int rememberValue1 = value1


value1 = value2
value2 = rememberValue1

The numbers were


rearranged into the
proper order
The numbers were
initially in order
The numbers are in
order
What is the Output?
int m = 5;
int n = 10;

if (m < n)
++m;
++n;

cout << " m = " << m << " n = " << n <<
endl;
The If-Else Statement
Syntax
if (Expression)
Action1
else
Action2
Expression
If Expression is true then execute
Action1 otherwise execute Action2 false
true
if (v == 0) {
cout << "v is 0";
Action1 Action2
}
else {
cout << "v is not 0";
}
Finding the Max
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
int Max;
if (Value1 < Value2) {
Max = Value2;
}
else {
Max = Value1;
}
cout << "Maximum of inputs is: " << Max << endl;
Finding the Max
Is Value2 larger than Value1

Yes, it is . So Value2 is
larger than Value1. In
this case, Max is set No, its not. So Value1
to Value2 is at least as large as
Value2. In this case,
Value1 < Value2 Max is set to Value1
true false

Max = Value2 Max = Value1

Either case, Max is set


correctly
Selection

It is often the case that depending upon the value of an


expression we want to perform a particular action

Two major ways of accomplishing this choice

if-else-if statement
– if-else statements “glued” together

Switch statement
– An advanced construct
An If-Else-If Statement
if ( nbr < 0 ){
cout << nbr << " is negative" << endl;
}
else if ( nbr > 0 ) {
cout << nbr << " is positive" << endl;
}
else {
cout << nbr << " is zero" << endl;
}
Process the response
by using the switch statement

27
What is
the switch Statement

Similar to the if statement


Can list any number of branches
Used in place of nested if statements
Used only with integer expressions
(true/false or int or char)
Avoids confusion of deeply nested if
statements
28
The switch Statement
Syntax
switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
case valueN: statementN;
break;
default: statement;
}

expression must return an integer value, i.e. be an integer


The switch Statement
with char expression
switch (choice)
{
case 1: cout << “The greatest ” << endl;
break;
case 2: cout << “Exciting team ”<< endl;
break
case 3: cout << “Boring ” << endl;
break;
case 4: cout << “Bye Bye” << endl;
}

//next statement
What is the purpose of the break statement?
The break Statement prevents “fall through”
it makes the computer jump out of the current
block, recall that the switch statement will execute
all statements below the point of entering the
statement. This can be a problem.
The switch Statement illustrate fall
through again

switch (choice){
case 1: cout << “The greatest ” << endl;
case 2: cout << “Exciting team ”<< endl;
case 3: cout << “Boring ” << endl;
case 4: cout << “Bye Bye << endl;
}
The switch Statement

What will be the output when the user enters 1?


The greatest
Exciting team
Boring
Bye Bye
The switch Statement

What will be the output when the user enters 2?


Exciting team
Boring
Bye Bye
The switch Statement

What will be the output when the user enters 3?


Boring
Bye Bye
The switch Statement

What will be the output when the user enters 4?


Bye Bye
Classic use of switch Statements:
for Menu processing
* * * * Menu * * * *

1. Man United
2. Chelsea
3. Arsenal
4. Quit

Choose either 1, 2, 3 or 4:
Example program to Demo
#include <iostream> //see displaymenu3.cpp
Using namespace std;
void DisplayMenu(void);

int main(void) {
int choice;
DisplayMenu();
cin >> choice;

switch (choice) {
case 1: cout << “The greatest“ << endl;
case 2: cout << “Exciting team“ << endl;
case 3: cout << “Boring“ << endl;
case 4: cout << “Bye Bye << endl;
};
return 0;
}
void DisplayMenu(void) {
cout << "*********** MENU **************\n";
cout <<endl;
cout << " 1. Man United" << endl;
cout << " 2. Chelsea" << endl;
cout << " 3. Arsenal" << endl;
cout << endl;
cout << "Please choose 1, 2 or 3 : ";
} 38
The switch Default Statement captures
errors or perform default action
e.g. if user enter any other number
switch (choice){
case 1: cout << “The greatest ” << endl;
break;
case 2: cout << “Exciting team ”<< endl;
break;
case 3: cout << “Boring ” << endl;
break;
case 4: cout << “Bye Bye “ << endl;
break;
default: “Incorrect choice” << endl;
}
Nested Switch Statements
For example:
switch( CarType )
{
case MONDEO:
switch( EngineCapacity)
{
case 1500:cout << “This is underpowered “;
break;
case 1800: cout << “This is just right”;
break;
case 2000: cout<<“This is expensive to run”;
}; //closes second switch
case FIESTA: break;
default: cout << “Unknown model”;
} //closes first switch
40
Problems with switch

Strange rules, once a condition is tested true


execution proceeds until break or end of
switch.
Control “falls through” the switch
Get in the habit of always putting breaks in and
putting a default condition in.
Less satisfactory to use where floats or
Boolean expressions are tested.
Putting in semi colon ‘;’after case rather than
colon ‘:’
41
Further Control Structures
I will go over some important topics today.
Loops and conditionals are essential for ones
development in any programming language.
We will look at the three types of looping
mechanisms
for
do-while
while
We will also look again at the if statement only
if it is required.

42
Display a menu
Simple Menus
1. Program displays a menu of choices
2. User enters a choice
3. Program responds to choice
4. Go back to to 1

43
Display a menu
Simple DisplayMenu() function
#include <iostream>

void DisplayMenu(void);

int main( ) {
function prototype consisting of
<type> function name (types of parameters);

return 0; So void here means no return type or parameters


expected. It is not required to use void here.
}

44
Display a menu
Simple DisplayMenu() function
#include <iostream>

void DisplayMenu(void);
Definition:
like a mini program
int main() {
or sub program

return 0;
}

void DisplayMenu(void) {
cout << “*********** MENU **************\n”;
cout <<endl;
cout << “ 1. Man United” << endl;
cout << “ 2. Chelsea” << endl;
cout << “ 3. Arsenal” << endl;
cout << “ 4. Quit” << endl;
cout << endl;
cout << “Please choose 1, 2, 3 or 4 : “;
}
45
Display a menu
Simple DisplayMenu() function
#include <iostream>

void DisplayMenu(void);
Function call
int main() {
int response; from within
main()
DisplayMenu();

return 0;
}

void DisplayMenu(void) {
cout << “*********** MENU **************\n”;
cout <<endl;
cout << “ 1. Man United” << endl; Prompt
cout << “ 2. Chelsea” << endl;
cout << “ 3. Arsenal” << endl;
cout << “ 4. Quit” << endl;
cout << endl;
cout << “Please choose 1, 2, 3 or 4 : “; 46
}
Recall Purpose of
Loops/Repetition
To apply the same steps again and
again to a block of statements.
Recall a block of statement is one or
more statement, block usually defined
by braces { … } with syntactically correct
statements inside.

47
Most Common Uses of Loops
You should master all these!
For counting
For accumulating, i.e. summing
For searching
For sorting
For displaying tables
For data entry – from files and users
For menu processing
For list processing

48
Types of loops

while
for
do..while

49
C/C++ Loop Structures
Pre-test (the test is made before entering
the loop)
while loops
– general purpose
– Event controlled (variable condition)
for loops
– When you know how many times (fixed condition)
– When you process arrays (more in later lectures)
Post-test (the test is done at the end of the
loop)
do … while loops
– When you do not know how many times, but you know
you need at least one pass. 50
– Data entry from users
Do-While Statement
Is a looping control structure in which the loop
condition is tested after each iteration of the
loop.

SYNTAX
do
{
Statement

} while (Expression) ; //note semi colon

Loop body statement can be a single statement or a block.


51
Function Using Do-While
void GetYesOrNo ( char response )
//see UseofFunction1.cpp
// Inputs a character from the user
// Postcondition: response has been input
// && response == ‘y’ or ‘n’
{
do
{
cin >> response ; // skips leading whitespace

if ( ( response != ‘y’ ) && ( response != ‘n’ ) )


cout << “Please type y or n : “ ;

} while ( ( response != ‘y’ ) && ( response != ‘n’ ) ) ;


}
52 52
Do-While Loop vs. While Loop

POST-TEST loop PRE-TEST loop


(exit-condition) (entry-condition)
The looping condition The looping condition
is tested after is tested before
executing the loop executing the loop
body. body.
Loop body is always Loop body may not
executed at least be executed at all.
once.
53
Do-While Loop
DO

Statement

WHILE

Expression
TRUE
FALSE

When the expression is tested and found to be false,


the loop is exited and control passes to the
statement that follows the do-while statement. 54
The for Statement Syntax
start condition while condition change expression

Example:
for (count=1; count < 7; count++)
{
cout << count << endl;
}
//next C++ statements;
The for Statement
Used as a counting loop
Used when we can work out in advance the
number of iterations, i.e. the number of times
that we want to loop around.
Semicolons separate the items in the for loop
block
There is no semi colon at the end of the for loop
definition at the beginning of the statement
A Simple Example
Create a table with a for loop
int num;
cout << "NUMBER\tSQUARE\tCUBE\n“;
cout << "------\t------\t----\n";

for (num = 1; num < 11; num++) {


cout << num << “\t“;
cout << num * num << “\t“;
cout << num * num * num<<“\n";
}//see useofFunction2.cpp
NUMBER SQUARE CUBE
---------- ---------- ------
1 1 1
2 4 8
. . .
. . .
10 100 1000

You might also like