SlideShare a Scribd company logo
CONDITIONAL
STATEMENTS
2
INTRODUCTION
Before writing a program
 Have a thorough understanding of problem
 Carefully plan your approach for solving it
While writing a program
 Know what “building blocks” are available
 Use good programming principles
3
ALGORITHMS
Computing problems
 Solved by executing a series of actions in a specific order
Algorithm is a procedure determining
 Actions to be executed
 Order to be executed
 Example: recipe
Program control
 Specifies the order in which statements are executed
4
PSEUDOCODE
Pseudocode
 Artificial, informal language used to develop algorithms
 Similar to everyday English
Not executed on computers
 Used to think out program before coding
 Easy to convert into C++ program
 Only executable statements
 No need to declare variables
5
CONTROL STRUCTURES
Flowchart
 Graphical representation of an algorithm
 Special-purpose symbols connected by arrows (flowlines)
 Rectangle symbol (action symbol)
 Any type of action
 Oval symbol
 Beginning or end of a program, or a section of code
(circles)
Single-entry/single-exit control structures
 Connect exit point of one to entry point of the next
 Control structure stacking
BASIC FLOWCHART SYMBOLS
6
SAMPLE FLOW CHART
7
8
CONTROL STRUCTURES
Sequential execution
 Statements executed in order
Transfer of control
 Next statement executed not next one in sequence
3 control structures (Bohm and Jacopini)
 Sequence structure
 Programs executed sequentially by default
 Selection structures
 if, if/else, switch
 Repetition structures
 while, do/while, for
FLOW OF CONTROL
Unless specified otherwise, the order of statement execution
through a function is linear: one statement after another in
sequence
Some programming statements allow us to:
 decide whether or not to execute a particular statement
 execute a statement over and over, repetitively
These decisions are based on boolean expressions (or
conditions) that evaluate to true or false
The order of statement execution is called the flow of control
OVERVIEW
 Many times we want programs to make decisions
 What drink should we dispense from the vending machine?
 Should we let the user withdraw money from this account?
 We make this choice by looking at values of variables
 When variables meet one condition we do one thing
 When variables do not meet condition we do something else
 To make decisions in a program we need conditional
statements that let us take different paths through code
10
OVERVIEW
A conditional statement lets us choose which statement
will be executed next
Therefore they are sometimes called selection
statements
Conditional statements give us the power to make basic
decisions
OVERVIEW
 In C++ there are three types of conditional statements:
 The if statement
 The if-else statement
 The switch statement
 Lesson objectives:
 Learn how logical expressions are written
 Learn the syntax and semantics of conditional statements
 Study example programs showing their use
 Complete lab tasks on conditional statements
 Complete programming assignments using conditional
statements
12
CONDITIONAL
STATEMENTS
PART 1
LOGICAL EXPRESSIONS
LOGICAL
EXPRESSIONS
 All conditional statements in C++ make use of logical
expressions that are true/false statements about data
 Simple logical expressions are of the form:
(data operator data)
 Data terms in logical expressions can be variables,
constants or arithmetic expressions
 C++ evaluates logical expressions from left to right to see
if they are true/false
14
LOGICAL
EXPRESSIONS
 The C++ relational operators are:
< less than
> greater than
<= less than or equal
>= greater than or equal
== equal to
!= not equal to
15
LOGICAL
EXPRESSIONS
 Some examples:
 (17 < 42) is true
 (42 > 17) is true
 (17 == 42) is false
 (42 != 17) is true
 ((17 + 10) > (42 – 2)) is false
 ((17 * 3) <= (17 + 17 + 17) is true
16
LOGICAL
EXPRESSIONS
 When integer variables a = 17 and b = 42
 (a < b) is true
 (a >= b) is false
 (a == 17) is true
 (a != b) is true
 ((a + 17) == b) is false
 ((42 – a) < b) is true
17
LOGICAL
EXPRESSIONS
 Warning: Do not use a single = for checking equality
 This will attempt to do assignment instead
 The logical expression will not check for equality
 Warning: Do not use =<, =>, =! to compare data values
 These are invalid operators
 You will get a compiler error
18
COMPLEX LOGICAL
EXPRESSIONS
 Simple logical expressions have limited power
 To solve this problem, we can combine simple logical
expressions to get complex logical expressions
 This is useful for more realistic data comparison tasks
 The basic syntax is: (expression operator expression)
 Expression can be a simple or complex logical expression
 The C++ logical operators are:
&& and
|| or
! not
19
COMPLEX LOGICAL
EXPRESSIONS
 Truth tables are often be used to enumerate all possible
values of a complex logical expression
 We make columns for all logical expressions
 Each row illustrates one set of input values
 The number of rows is always a power of 2
20
A B A && B A || B
TRUE TRUE TRUE TRUE
TRUE FALSE FALSE TRUE
FALSE TRUE FALSE TRUE
FALSE FALSE FALSE FALSE
COMPLEX LOGICAL
EXPRESSIONS
 C++ evaluates complex logical expressions from left to right
 (exp1 && exp2) will be true if both exp are true
 (exp1 && exp2 && exp3) will be true if all exp are true
 (exp1 || exp2 || exp3) will be true if any exp is true
 C++ has a feature called “conditional evaluation” that will
stop the evaluation early in some cases
 (exp1 && exp2) will be false if exp1 is false
 (exp1 || exp2) will be true if exp1 is true
 In both cases, we do not need to evaluate exp2
21
COMPLEX LOGICAL
EXPRESSIONS
 Complex logical expressions
 ((17 < 42) && (42 < 17)) is false, because second half is false
 ((17 <= 42) || (42 <= 17)) is true, because first half is true
 When float variables x = 3.14 and y = 7.89
 ((x < 4) && (y < 8)) is true, because both halves are true
 ((x > 3) && (y > 8)) is false, because second half is false
 ((x < 4) || (y > 8)) is true, because first half is true
 ((x < 3) || (y < 8)) is true, because second half is true
 ((x > 4) || (y > 8)) is false, because both halves are false
22
THE NOT OPERATOR
 The not operator ‘!’ in in C++ reverses the value of any
logical expression
 Logically “not true” is same as “false”
 Logically “not false” is same as “true”
 The C++ syntax for the not operator is: ! expression
 This is a “unary” operator since there is just one
expression to the right of the not operator
23
THE NOT OPERATOR
 Examples with integer variables a = 7 and b = 3
 (a > b) is true ! (a > b) is false
 (a <= b) is false ! (a <= b) is true
 (a == b) is false ! (a == b) is true
 (a != b) is true ! (a != b) is false
24
THE NOT OPERATOR
 We can often “move the not operation inside” a simple
logical expression
 To do this simplification, we need to remove the ! operator
and reverse the logic of the relational operator
 !(a < b) same as (a >= b)
 !(a <= b) same as (a > b)
 !(a > b) same as (a <= b)
 !(a >= b) same as (a < b)
 !(a == b) same as (a != b)
 !(a != b) same as (a == b)
25
THE NOT OPERATOR
 We can extend truth tables to illustrate the not operator
 Add new columns showing !A and !B and their use in
complex logical expressions
26
A B !A !B A && B A || B !A && !B !A || !B
TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE
TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE
FALSE TRUE TRUE FALSE FALSE TRUE FALSE TRUE
FALSE FALSE TRUE TRUE FALSE FALSE TRUE TRUE
Notice anything
interesting here?
THE NOT OPERATOR
 We can extend truth tables to illustrate the not operator
 Add new columns showing !A and !B and their use in
complex logical expressions
27
A B !A !B A && B A || B !A && !B !A || !B
TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE
TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE
FALSE TRUE TRUE FALSE FALSE TRUE FALSE TRUE
FALSE FALSE TRUE TRUE FALSE FALSE TRUE TRUE
The same pattern
occurs here too
THE NOT OPERATOR
 From the truth table we can see that:
!(A || B) is the same as !A && ! B
!(A && B) is the same as !A || ! B
 This rule is known as “De Morgan’s Law”
 It allows us to simplify a complex logical expression by
“moving the not operation to expression operands”
28
THE NOT OPERATOR
 To apply De Morgan’s Law, we must change the logical
operator and the expressions
 The && operator changes into ||
 The || operator changes into &&
 The ! is applied to both expressions
 Remember, two not operators side by side cancel each
other out so they can both be removed
29
THE NOT OPERATOR
 When exp1 and exp2 are simple logical expressions
 !(exp1 && exp2) same as (!exp1 || !exp2)
 !(exp1 || exp2) same as (!exp1 && !exp2)
 !(!exp1 || !exp2) same as (!!exp1 && !!exp2) or (exp1 && exp2)
 !(!exp1 && !exp2) same as (!!exp1 || !!exp2) or (exp1 || exp2)
 Hence, there are many different ways to represent the same
logical expression
30
THE NOT OPERATOR
 Examples with float variables x = 4.3 and y = 9.2
 ((x < 5) && (y < 10)) is true
 !((x < 5) && (y < 10)) is false
 ( !(x < 5) || !(y < 10)) is false
 ((x >= 5) || (y >= 10)) is false
 !((x >= 5) || (y >= 10)) is true
 ( !(x >= 5) && !(y >= 10)) is true
 ((x < 5) && (y < 10)) is true
31
SUMMARY
 In this section, we have focused on how logical
expressions can be written in C++
 We have seen how relational operators (<, <=, >, >=, ==,
and !=) can be used to create simple logical expressions
 We have seen how logical operators (&& and !!) can be
used to make more complex logical expressions
 Finally, we have seen how the not operator (!) can be used
to reverse the true/false value of logical expressions
32
CONDITIONAL
STATEMENTS
PART 2
IF STATEMENTS
THE IF STATEMENT
 Sometimes we want to selectively execute a block of code
 The C++ syntax of the if statement is:
if ( logical expression )
{
//Block of code if expression is true
statement1;
statement2;
}
 When expression is true, the block of code is executed
 When expression is false, the block of code is skipped
34
THE IF STATEMENT
Allows statements to be conditionally executed or skipped
over
Models the way we mentally evaluate situations:
 "If it is raining, take an umbrella."
 "If it is cold outside, wear a coat."
35
FLOWCHART FOR
EVALUATING A DECISION
36
ANOTHER
FLOWCHART
37
THE IF STATEMENT
The if statement has the following syntax:
if ( condition )
statement;
if is a C
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
THE IF STATEMENT
 Programming style suggestions:
 The block of code should be indented 3-4 spaces to aid
program readability
 If the block of code is only one line long the { } brackets can
be omitted
 Never put a semi-colon directly after the Boolean
expression in an if statement
 The empty statement between ) and ; will be selectively
executed based on the logical expression value
 The block of code directly below if statement will always be
executed, which is probably not what you intended
39
THE IF STATEMENT
 We can visualize the program’s if statement decision
process using a “flow chart” diagram
40
Logical
expression
Block of code
true
false
THE IF STATEMENT
 If the logical expression is true, we take one path through
the diagram (executing the block of code)
41
Logical
expression
Block of code
true
false
THE IF STATEMENT
 If the logical expression is false, we take a different path
through the diagram (skipping over the block of code)
42
Logical
expression
Block of code
true
false
THE IF STATEMENT
// Simple if statement
int a, b;
cin >> a >> b;
if (a < b)
cout << “A is smaller than Bn”;
43
THE IF STATEMENT
// One line block of code
int a, b;
cin >> a >> b;
if (a == b)
cout << “A is equal to Bn”;
44
THE IF STATEMENT
// Block of code that never executes
if (1 == 2)
cout << “This code will never executen”;
45
THE IF STATEMENT
// Block of code that always executes
if (true)
cout << “This code will always executen”;
46
47
IF SELECTION
STRUCTURE
Flowchart of pseudocode statement
true
false
grade >= 60 print “Passed”
A decision can be made on
any expression.
zero - false
nonzero - true
Example:
3, - 4 is true
Translation into C++
If student’s grade is greater than or equal to 60
Print “Passed”
if ( grade >= 60 )
cout << "Passed";
WHAT IS THE OUTPUT?
int m = 5;
int n = 10;
if (m < n)
++m;
++n;
cout << " m = " << m << " n = " << n << endl;
WHAT IS THE OUTPUT?
int m = 10;
int n = 5;
if (m < n)
++m;
++n;
cout << " m = " << m << " n = " << n << endl;
THE IF-ELSE
STATEMENT
 Sometimes we need to handle two alternatives in our code
 The C++ syntax of the if-else statement is:
if ( logical expression )
{
// Block of code to execute if expression is true
}
else
{
// Block of code to execute if expression is false
}
50
THE IF-ELSE
STATEMENT
An else clause can be added to an if statement to make an if-
else statement
if ( condition )
statement1;
else
statement2;
• If the condition is true, statement1 is executed;
if the condition is false, statement2 is executed
• One or the other will be executed, but not both
THE IF-ELSE
STATEMENT
 Programming style suggestions:
 Type the “if line” and the “else line” and the { } brackets so
they are vertically aligned with each other
 Do not put a semi-colon after the “if line” or the “else line” or
you will get very strange run time errors
 The two blocks of code should be indented 3-4 spaces to aid
program readability
 If either block of code is only one line long the { } brackets can
be omitted
52
THE IF-ELSE
STATEMENT
 We can visualize the program’s if-else statement decision
process using a “flow chart” diagram
53
Logical
expression
Block of code
executed if true
true
false
Block of code
executed if false
THE IF-ELSE
STATEMENT
 If the logical expression is true, we take one path through
the diagram (executing one block of code)
54
Logical
expression
Block of code
executed if true
true
false
Block of code
executed if false
THE IF-ELSE
STATEMENT
 If the logical expression is false, we take one path through
the diagram (executing the other block of code)
55
Logical
expression
Block of code
executed if true
true
false
Block of code
executed if false
THE IF-ELSE
STATEMENT
// Simple if-else example
if ((a > 0) && (b > 0))
{
c = a / b;
a = a - c;
}
else
{
c = a * b;
a = b + c;
}
56
THE IF-ELSE
STATEMENT
// Ugly if-else example
if (a < b) {
c = a * 3;
a = b - c; } else
a = c + 5;
 This code is nice and short but it is hard to read
57
THE IF-ELSE
STATEMENT
// Pretty if-else example
if (a < b)
{
c = a * 3;
a = b - c;
}
else
a = c + 5;
 This code takes more lines but it is easier to read
58
TESTING A SERIES OF
CONDITIONS
Use if … else … if sequences to test a series of
conditions:
If your score is over 90 your letter grade is A else if your
score is over 80 your letter grade is B else your letter grade
is C.
59
GRADE CALCULATION
EXAMPLE
 How can we convert test scores to letter grades?
 We are given numerical values between 0..100
 We want to output A,B,C,D,F letter grades
 We will want series of if-else statements
 If test score between 90..100 output A
 Else if score between 80..89 output B
 Else if score between 70..79 output C
 Else if score between 60..69 output D
 Else if score between 0..59 output F
60
GRADE CALCULATION
EXAMPLE
// Program to convert test scores into letter grades
#include <iostream>
using namespace std;
int main()
{
// Local variable declarations
// Read test score
// Calculate grade
// Print output
return 0;
}
61
The first step is to
write comments in
the main program to
explain our approach
GRADE CALCULATION
EXAMPLE
// Program to convert test scores into letter grades
#include <iostream>
using namespace std;
int main()
{
// Local variable declarations
float Score = 0;
char Grade = '?' ;
// Read test score
cout << “Enter test score: “;
cin >> Score;
…
62
We add code to the
main program to get
the input test score
GRADE CALCULATION
EXAMPLE
…
// Local variable declarations
float Score = 0;
char Grade = '?' ;
// Read test score
cout << “Enter test score: “;
cin >> Score;
// Calculate grade
if (Score >= 90)
Grade = 'A';
// Print output
cout << “Grade: ” << Grade;
…
63
We add more code
calculate one letter
grade and print output
GRADE CALCULATION
EXAMPLE
…
// Calculate grade
if (Score >= 90)
Grade = 'A';
else if (Score >= 80)
Grade = 'B';
else if (Score >= 70)
Grade = 'C';
else if (Score >= 60)
Grade = 'D';
else
Grade = 'F';
…
64
We add more code to
calculate the remaining
letter grades
Do you think there will be any issues if we use if instead of else if
????
GRADE CALCULATION
EXAMPLE
 How should we test the grade calculation program?
 Start with values we know are in the middle of the
A,B,C,D,F letter ranges (e.g. 95,85,75,65,55)
 Then test values “on the border” of the letter grade ranges
to make sure we have our “>=“ and “>” conditions right
(e.g. 79,80,81)
 Then test values that are outside the 0..100 range to see
what happens – is this what we want?
 Finally, see what happens if the user enters something
other than an integer value (e.g. 3.14159, “hello”)
65
RANGE CHECKING
Used to test to see if a value falls inside a range:
if (grade >= 0 && grade <= 100)
cout << "Valid grade";
Can also test to see if value falls outside of range:
if (grade <= 0 || grade >= 100)
cout << "Invalid grade";
Cannot use mathematical notation:
if (0 <= grade <= 100) //doesn’t work!
66
COMPARING
CHARACTERS
Characters are compared using their ASCII values
'A' < 'B'
 The ASCII value of 'A' (65) is less than the ASCII value of
'B'(66)
'1' < '2'
 The ASCII value of '1' (49) is less than the ASCI value of '2'
(50)
Lowercase letters have higher ASCII codes than uppercase
letters, so 'a' > 'Z'
67
SUMMARY
 In this section we have studied the syntax and use of the
C++ if statement and the if-else statement
 We have also seen how flow chart diagrams can be used
to visualize different execution paths in a program
 Finally, we showed how if statements can be used to
implement a simple grade calculation program
68
CONDITIONAL
STATEMENTS
PART 3
NESTED IF STATEMENTS
NESTED IF
STATEMENTS
We can have two or more if statements inside each other to
check multiple conditions
 These are called nested if statements
Nested if statements can be used to test more than one
condition
Use indentation to reflect nesting and aid readability
 Typically indent 3-4 spaces or one tab
Need to take care when matching up { } brackets
 This way you can decipher the nesting of conditions
70
NESTED IF
STATEMENTS
if ( logical expression1 )
{
if ( logical expression2 )
{
// Statements to execute if expressions1 and expression2 are true
}
else
{
// Statements to execute if expression1 true and expression2 false
}
}
else
{
// Statements to execute if expression1 false
}
71
FLOWCHART FOR A
NESTED IF STATEMENT
72
NESTED IF CODE
// Determine loan qualification
if (employed == ‘y’)
{
if (recentGrad == ‘y’)
{
cout << “You qualify!”
}
}
Note: this could be done with one if and two conditions.
73
NESTED IF
STATEMENTS
// Simple nested if example
cin >> a >> b;
if (a < b)
{
cout << “A is smaller than Bn”;
if ((a > 0) && (b > 0))
cout << “A and B are both positiven”;
else
cout << “A or B or both are negativen”;
}
74
NESTED IF
STATEMENTS
// Ugly nested if example
if (a > 0) {
if (b < 0) {
a = 3 * b;
c = a + b; } }
else {
a = 2 * a;
c = b / a; }
 It is hard to see what condition the else code goes with
75
NESTED IF
STATEMENTS
// Pretty nested if example
if (a > 0)
{
if (b < 0)
{
a = 3 * b;
c = a + b;
}
}
else
{
a = 2 * a;
c = b / a;
}
76
BOOLEAN VARIABLES
 In C++ we can store true/false values in Boolean variables
 The constants “true” and “false” can be used to initialize
these variables
 bool Done = true;
 bool Quit = false;
 Boolean expressions can also be used to initialize these
variables
 bool Positive = (a >= 0);
 bool Negative = (b < 0);
77
BOOLEAN VARIABLES
 Boolean variables and true/false constants can also be
used in logical expressions
 (Done == true) is true
 (Quit != true) is true
 (Done == Quit) is false
 (true == Positive) is true
 ((a < b) == false) is false
 (Negative) is false
78
BOOLEAN VARIABLES
 Internally C++ stores Boolean variables as integers
 0 is normally used for false
 1 is normally used for true
 Any value != 1 is also considered true
 It is considered “bad programming style” to use integers
instead of true/false
 bool Good = 0;
 bool Bad = 1;
 bool Ugly = a;
79
BOOLEAN VARIABLES
 Integers are used when writing Boolean values
 cout << Good will print 0
 cout << Bad will print 1
 cout << Ugly will also print 1
 Integers are also used when reading Boolean values
 cin >> Good;
 Entering 0 sets Good variable to false
 Entering any value >= 1 sets Good variable to true
 Entering value < 0 also sets Good variable to true
80
PRIME NUMBER
EXAMPLE
 How can we test a number to see if it is prime?
 We are given numerical values between 1..100
 We need to see if it has any factors besides 1 and itself
 We need some nested if statements
 Test if input number is between 1..100
 If so, then test if 2,3,5,7 are factors of input number
 Then print out “prime” or “not prime”
81
PRIME NUMBER
EXAMPLE
// Check for prime numbers using a factoring approach
#include <iostream>
using namespace std;
int main()
{
// Local variable declarations
// Read input parameters
// Check input is valid
// Check if number is prime
// Print output
return 0;
}
82
For the first version
of program we just
write comments in
the main program to
explain our approach
PRIME NUMBER
EXAMPLE
// Check for prime numbers using a factoring approach
#include <iostream>
using namespace std;
int main()
{
// Local variable declarations
int Number = 0;
bool Prime = true;
// Read input parameters
cout << “Enter a number [1..100]:”;
cin >> Number;
83
For the second
version of program
we initialize variables
and read the input
value from user
PRIME NUMBER
EXAMPLE
…
cout << “Enter a number [1..100]:”;
cin >> Number;
// Check input is valid
if ((Number < 1) || (Number > 100))
cout << “Error: Number is out of rangen”;
else
{
// Check if number is prime
// Print output
}
84
For the next version
of the program we
add code to verify the
range of input value
PRIME NUMBER
EXAMPLE
// Check if number is prime
if (Number == 1)
Prime = false;
if ((Number > 2) && (Number % 2 == 0))
Prime = false;
if ((Number > 3) && (Number % 3 == 0)) Prime = false;
if ((Number > 5) && (Number % 5 == 0)) Prime = false;
if ((Number > 7) && (Number % 7 == 0)) Prime = false;
// Print output
if (Prime)
cout << “Number “ << Number << “ IS primen”;
else
cout << “Number “ << Number << “ is NOT primen”;
85
In the final
version we finish
the prime number
calculation and
print the output
PRIME NUMBER
EXAMPLE
 How should we test the prime number program?
 Test the range checking code by entering values “on the
border” of the input range (e.g. 0,1,2 and 99,100,101)
 Test program with several values we know are prime
 Test program with several values we know are not prime
 To be really compulsive we could test all values between
1..100 and compare to known prime numbers
 What is wrong with this program?
 It only works for inputs between 1..100
 It will not “scale up” easily if we extend this input range
86
SUMMARY
 In this section we showed how if statements and if-else
statements can be nested inside each other to create more
complex paths through a program
 We also showed how proper indenting is important to read
and understand programs with nested if statements
 We have seen how Boolean variables can be used to store
true/false values in a program
 Finally, we used an incremental approach to create a
program for checking the factors of input numbers to see
if they are prime or not
87
EXAMPLE: WAGES.CPP
Write a C++ program that calculates weekly wages for hourly
employees.
 Regular hours 0 - 40 are paid at $10/hours.
 Overtime (> 40 hours per week) is paid at 150%
CONDITIONAL
STATEMENTS
PART 4
SWITCH STATEMENTS
SWITCH STATEMENTS
 The switch statement is convenient for handling multiple
branches based on the the value of one decision variable
 The program looks at the value of the decision variable
 The program jumps directly to the matching case label
 The statements following the case label are executed
 Special features of the switch statement:
 The “break” command at the end of a block of statements
will make the program jump to the end of the switch
 The program executes the statements after the “default”
label if no other cases match the decision variable
90
SWITCH STATEMENTS
switch ( decision variable )
{
case value1 :
// Statements to execute if variable equals value1
break;
case value2:
// Statements to execute if variable equals value2
break;
...
default:
// Statements to execute if variable not equal to any value
}
91
SWITCH STATEMENTS
int Number = 0;
cin >> Number;
switch (Number)
{
case 0:
cout << “This is nothing << endl;
break;
case 7:
cout << “My favorite number” << endl;
break;
92
SWITCH STATEMENTS
case 21:
cout << “Lets go for a drink” << endl;
break;
case 42:
cout << “The answer to the ultimate question” << endl;
break;
default:
cout << “This number is boring” << endl;
}
93
SWITCH STATEMENTS
 The main advantage of switch statement over a sequence
of if-else statements is that it is much faster
 Jumping to blocks of code is based on a lookup table
instead of a sequence of variable comparisons
 The main disadvantage of switch statements is that the
decision variable must be an integer (or a character)
 We can not use a switch with a float or string decision
variable or with complex logical expressions
94
MENU EXAMPLE
 How can we create a user interface for banking?
 Assume user selects commands from a menu
 We need to see read and process user commands
 We can use a switch statements to handle menu
 Ask user for numerical code for user command
 Jump to the code to process that banking operation
 Repeat until the user quits the application
95
MENU EXAMPLE
// Simulate bank deposits and withdrawals
#include <iostream>
using namespace std;
int main()
{
// Local variable declarations
// Print command prompt
// Read user input
// Handle banking command
return 0;
}
96
For the first version
of program we just
write comments in
the main program to
explain our approach
MENU EXAMPLE
…
// Local variable declarations
int Command = 0;
// Print command prompt
cout << “Enter command number:n”;
// Read user input
cin >> Command;
…
97
For the next version
of program we add
the code to read the
user command
MENU EXAMPLE
// Handle banking command
switch (Command)
{
case 0: // Quit code
break;
case 1: // Deposit code
break;
case 2: // Withdraw code
break;
case 3: // Print balance code
break;
}
98
Then we add the
skeleton of the switch
statement to handle
the user command
MENU EXAMPLE
// Simulate bank deposits and withdrawals
#include <iostream>
using namespace std;
int main()
{
// Local variable declarations
int Command = 0;
int Money = 0;
int Balance = 100;
// Print command prompt
cout << “Enter command number:n”
<< “ 0 - quitn”
<< “ 1 - deposit moneyn”
<< “ 2 - withdraw moneyn”
<< “ 3 - print balancen”;
99
In the final version
add bank account
variables and add
code to perform
banking operations
MENU EXAMPLE
// Read and handle banking commands
cin >> Command;
switch (Command)
{
case 0: // Quit code
cout << “See you later!” << endl;
break;
case 1: // Deposit code
cout << “Enter deposit amount: “;
cin >> Money;
Balance = Balance + Money;
break;
100
MENU EXAMPLE
case 2: // Withdraw code
cout << “Enter withdraw amount: “;
cin >> Money;
Balance = Balance - Money;
break;
case 3: // Print balance code
cout << “Current balance = “ << Balance << endl;
break;
default: // Handle other values
cout << “Ooops try again” << endl;
break;
}
// Print final balance
cout << “Final balance = “ << Balance << endl;
}
101
MENU EXAMPLE
 How should we test this program?
 Test the code by entering all valid menu commands
 What happens if we enter an invalid menu command?
 What happens if we enter an invalid deposit or withdraw
amount (e.g. negative input values)?
 What is wrong with this program?
 We might end up with a negative account balance
 There is only one bank account and zero security
102
SOFTWARE
ENGINEERING TIPS
 There are many ways to write conditional code
 Your task is to find the simplest correct code for the task
 Make your code easy to read and understand
 Indent your program to reflect the nesting of blocks of code
 Develop your program incrementally
 Compile and run your code frequently
 Anticipate potential user input errors
 Check for normal and abnormal input values
103
SOFTWARE
ENGINEERING TIPS
 Common programming mistakes
 Missing or unmatched ( ) brackets in logical expressions
 Missing or unmatched { } brackets in conditional statement
 Missing break statement at bottom of switch cases
 Never use & instead of && in logical expressions
 Never use | instead of || in logical expressions
 Never use = instead of == in logical expressions
 Never use “;” directly after logical expression
104
SUMMARY
 In this section we have studied the syntax and use of the
C++ switch statement
 We also showed an example where a switch statement
was used to create a menu-based banking program
 Finally, have discussed several software engineering tips
for creating and debugging conditional programs
105

More Related Content

Similar to Ref Lec 4- Conditional Statement (1).pptx

C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
jahanullah
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
guest58c84c
 
Ch05.pdf
Ch05.pdfCh05.pdf
Control statements in c
Control statements in cControl statements in c
Control statements in c
Sathish Narayanan
 
Ap Power Point Chpt3 B
Ap Power Point Chpt3 BAp Power Point Chpt3 B
Ap Power Point Chpt3 B
dplunkett
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
dplunkett
 
C++
C++ C++
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
Kathirvel Ayyaswamy
 
L05if
L05ifL05if
Control All
Control AllControl All
Control All
phanleson
 
MODULE_2_Operators.pptx
MODULE_2_Operators.pptxMODULE_2_Operators.pptx
MODULE_2_Operators.pptx
VeerannaKotagi1
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
Rasan Samarasinghe
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
bajiajugal
 
Operators
OperatorsOperators
Operators
Kamran
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection Statements
SzeChingChen
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
It Academy
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
Praveen M Jigajinni
 
Overview of C Language
Overview of C LanguageOverview of C Language
Overview of C Language
Prof. Erwin Globio
 
Lecture 07.pptx
Lecture 07.pptxLecture 07.pptx
Lecture 07.pptx
Mohammad Hassan
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
Viraj Shah
 

Similar to Ref Lec 4- Conditional Statement (1).pptx (20)

C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Ap Power Point Chpt3 B
Ap Power Point Chpt3 BAp Power Point Chpt3 B
Ap Power Point Chpt3 B
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
C++
C++ C++
C++
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
L05if
L05ifL05if
L05if
 
Control All
Control AllControl All
Control All
 
MODULE_2_Operators.pptx
MODULE_2_Operators.pptxMODULE_2_Operators.pptx
MODULE_2_Operators.pptx
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
Operators
OperatorsOperators
Operators
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection Statements
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
 
Overview of C Language
Overview of C LanguageOverview of C Language
Overview of C Language
 
Lecture 07.pptx
Lecture 07.pptxLecture 07.pptx
Lecture 07.pptx
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
 

More from BilalAhmad735613

tt21-uiit-new-100321.pdf
tt21-uiit-new-100321.pdftt21-uiit-new-100321.pdf
tt21-uiit-new-100321.pdf
BilalAhmad735613
 
presentation1-150701064721-lva1-app6891 (1).pdf
presentation1-150701064721-lva1-app6891 (1).pdfpresentation1-150701064721-lva1-app6891 (1).pdf
presentation1-150701064721-lva1-app6891 (1).pdf
BilalAhmad735613
 
Religion and Politics-stripped.ppt
Religion and Politics-stripped.pptReligion and Politics-stripped.ppt
Religion and Politics-stripped.ppt
BilalAhmad735613
 
abgfwtrxrh2rnwhpkxj7-signature-db587f84d4d53a9302a1faaf23f237f34f11f23d0db3be...
abgfwtrxrh2rnwhpkxj7-signature-db587f84d4d53a9302a1faaf23f237f34f11f23d0db3be...abgfwtrxrh2rnwhpkxj7-signature-db587f84d4d53a9302a1faaf23f237f34f11f23d0db3be...
abgfwtrxrh2rnwhpkxj7-signature-db587f84d4d53a9302a1faaf23f237f34f11f23d0db3be...
BilalAhmad735613
 
selfconfidenceppt-180820180740 (1).pdf
selfconfidenceppt-180820180740 (1).pdfselfconfidenceppt-180820180740 (1).pdf
selfconfidenceppt-180820180740 (1).pdf
BilalAhmad735613
 
PowerPoint-Transgender-Resilience.pdf
PowerPoint-Transgender-Resilience.pdfPowerPoint-Transgender-Resilience.pdf
PowerPoint-Transgender-Resilience.pdf
BilalAhmad735613
 

More from BilalAhmad735613 (6)

tt21-uiit-new-100321.pdf
tt21-uiit-new-100321.pdftt21-uiit-new-100321.pdf
tt21-uiit-new-100321.pdf
 
presentation1-150701064721-lva1-app6891 (1).pdf
presentation1-150701064721-lva1-app6891 (1).pdfpresentation1-150701064721-lva1-app6891 (1).pdf
presentation1-150701064721-lva1-app6891 (1).pdf
 
Religion and Politics-stripped.ppt
Religion and Politics-stripped.pptReligion and Politics-stripped.ppt
Religion and Politics-stripped.ppt
 
abgfwtrxrh2rnwhpkxj7-signature-db587f84d4d53a9302a1faaf23f237f34f11f23d0db3be...
abgfwtrxrh2rnwhpkxj7-signature-db587f84d4d53a9302a1faaf23f237f34f11f23d0db3be...abgfwtrxrh2rnwhpkxj7-signature-db587f84d4d53a9302a1faaf23f237f34f11f23d0db3be...
abgfwtrxrh2rnwhpkxj7-signature-db587f84d4d53a9302a1faaf23f237f34f11f23d0db3be...
 
selfconfidenceppt-180820180740 (1).pdf
selfconfidenceppt-180820180740 (1).pdfselfconfidenceppt-180820180740 (1).pdf
selfconfidenceppt-180820180740 (1).pdf
 
PowerPoint-Transgender-Resilience.pdf
PowerPoint-Transgender-Resilience.pdfPowerPoint-Transgender-Resilience.pdf
PowerPoint-Transgender-Resilience.pdf
 

Recently uploaded

Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
National Information Standards Organization (NISO)
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
deepaannamalai16
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
National Information Standards Organization (NISO)
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
giancarloi8888
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
melliereed
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
JomonJoseph58
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
سمير بسيوني
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
RamseyBerglund
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
BoudhayanBhattachari
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 

Recently uploaded (20)

Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 

Ref Lec 4- Conditional Statement (1).pptx

  • 2. 2 INTRODUCTION Before writing a program  Have a thorough understanding of problem  Carefully plan your approach for solving it While writing a program  Know what “building blocks” are available  Use good programming principles
  • 3. 3 ALGORITHMS Computing problems  Solved by executing a series of actions in a specific order Algorithm is a procedure determining  Actions to be executed  Order to be executed  Example: recipe Program control  Specifies the order in which statements are executed
  • 4. 4 PSEUDOCODE Pseudocode  Artificial, informal language used to develop algorithms  Similar to everyday English Not executed on computers  Used to think out program before coding  Easy to convert into C++ program  Only executable statements  No need to declare variables
  • 5. 5 CONTROL STRUCTURES Flowchart  Graphical representation of an algorithm  Special-purpose symbols connected by arrows (flowlines)  Rectangle symbol (action symbol)  Any type of action  Oval symbol  Beginning or end of a program, or a section of code (circles) Single-entry/single-exit control structures  Connect exit point of one to entry point of the next  Control structure stacking
  • 8. 8 CONTROL STRUCTURES Sequential execution  Statements executed in order Transfer of control  Next statement executed not next one in sequence 3 control structures (Bohm and Jacopini)  Sequence structure  Programs executed sequentially by default  Selection structures  if, if/else, switch  Repetition structures  while, do/while, for
  • 9. FLOW OF CONTROL Unless specified otherwise, the order of statement execution through a function is linear: one statement after another in sequence Some programming statements allow us to:  decide whether or not to execute a particular statement  execute a statement over and over, repetitively These decisions are based on boolean expressions (or conditions) that evaluate to true or false The order of statement execution is called the flow of control
  • 10. OVERVIEW  Many times we want programs to make decisions  What drink should we dispense from the vending machine?  Should we let the user withdraw money from this account?  We make this choice by looking at values of variables  When variables meet one condition we do one thing  When variables do not meet condition we do something else  To make decisions in a program we need conditional statements that let us take different paths through code 10
  • 11. OVERVIEW A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements Conditional statements give us the power to make basic decisions
  • 12. OVERVIEW  In C++ there are three types of conditional statements:  The if statement  The if-else statement  The switch statement  Lesson objectives:  Learn how logical expressions are written  Learn the syntax and semantics of conditional statements  Study example programs showing their use  Complete lab tasks on conditional statements  Complete programming assignments using conditional statements 12
  • 14. LOGICAL EXPRESSIONS  All conditional statements in C++ make use of logical expressions that are true/false statements about data  Simple logical expressions are of the form: (data operator data)  Data terms in logical expressions can be variables, constants or arithmetic expressions  C++ evaluates logical expressions from left to right to see if they are true/false 14
  • 15. LOGICAL EXPRESSIONS  The C++ relational operators are: < less than > greater than <= less than or equal >= greater than or equal == equal to != not equal to 15
  • 16. LOGICAL EXPRESSIONS  Some examples:  (17 < 42) is true  (42 > 17) is true  (17 == 42) is false  (42 != 17) is true  ((17 + 10) > (42 – 2)) is false  ((17 * 3) <= (17 + 17 + 17) is true 16
  • 17. LOGICAL EXPRESSIONS  When integer variables a = 17 and b = 42  (a < b) is true  (a >= b) is false  (a == 17) is true  (a != b) is true  ((a + 17) == b) is false  ((42 – a) < b) is true 17
  • 18. LOGICAL EXPRESSIONS  Warning: Do not use a single = for checking equality  This will attempt to do assignment instead  The logical expression will not check for equality  Warning: Do not use =<, =>, =! to compare data values  These are invalid operators  You will get a compiler error 18
  • 19. COMPLEX LOGICAL EXPRESSIONS  Simple logical expressions have limited power  To solve this problem, we can combine simple logical expressions to get complex logical expressions  This is useful for more realistic data comparison tasks  The basic syntax is: (expression operator expression)  Expression can be a simple or complex logical expression  The C++ logical operators are: && and || or ! not 19
  • 20. COMPLEX LOGICAL EXPRESSIONS  Truth tables are often be used to enumerate all possible values of a complex logical expression  We make columns for all logical expressions  Each row illustrates one set of input values  The number of rows is always a power of 2 20 A B A && B A || B TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE
  • 21. COMPLEX LOGICAL EXPRESSIONS  C++ evaluates complex logical expressions from left to right  (exp1 && exp2) will be true if both exp are true  (exp1 && exp2 && exp3) will be true if all exp are true  (exp1 || exp2 || exp3) will be true if any exp is true  C++ has a feature called “conditional evaluation” that will stop the evaluation early in some cases  (exp1 && exp2) will be false if exp1 is false  (exp1 || exp2) will be true if exp1 is true  In both cases, we do not need to evaluate exp2 21
  • 22. COMPLEX LOGICAL EXPRESSIONS  Complex logical expressions  ((17 < 42) && (42 < 17)) is false, because second half is false  ((17 <= 42) || (42 <= 17)) is true, because first half is true  When float variables x = 3.14 and y = 7.89  ((x < 4) && (y < 8)) is true, because both halves are true  ((x > 3) && (y > 8)) is false, because second half is false  ((x < 4) || (y > 8)) is true, because first half is true  ((x < 3) || (y < 8)) is true, because second half is true  ((x > 4) || (y > 8)) is false, because both halves are false 22
  • 23. THE NOT OPERATOR  The not operator ‘!’ in in C++ reverses the value of any logical expression  Logically “not true” is same as “false”  Logically “not false” is same as “true”  The C++ syntax for the not operator is: ! expression  This is a “unary” operator since there is just one expression to the right of the not operator 23
  • 24. THE NOT OPERATOR  Examples with integer variables a = 7 and b = 3  (a > b) is true ! (a > b) is false  (a <= b) is false ! (a <= b) is true  (a == b) is false ! (a == b) is true  (a != b) is true ! (a != b) is false 24
  • 25. THE NOT OPERATOR  We can often “move the not operation inside” a simple logical expression  To do this simplification, we need to remove the ! operator and reverse the logic of the relational operator  !(a < b) same as (a >= b)  !(a <= b) same as (a > b)  !(a > b) same as (a <= b)  !(a >= b) same as (a < b)  !(a == b) same as (a != b)  !(a != b) same as (a == b) 25
  • 26. THE NOT OPERATOR  We can extend truth tables to illustrate the not operator  Add new columns showing !A and !B and their use in complex logical expressions 26 A B !A !B A && B A || B !A && !B !A || !B TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE TRUE TRUE Notice anything interesting here?
  • 27. THE NOT OPERATOR  We can extend truth tables to illustrate the not operator  Add new columns showing !A and !B and their use in complex logical expressions 27 A B !A !B A && B A || B !A && !B !A || !B TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE TRUE TRUE The same pattern occurs here too
  • 28. THE NOT OPERATOR  From the truth table we can see that: !(A || B) is the same as !A && ! B !(A && B) is the same as !A || ! B  This rule is known as “De Morgan’s Law”  It allows us to simplify a complex logical expression by “moving the not operation to expression operands” 28
  • 29. THE NOT OPERATOR  To apply De Morgan’s Law, we must change the logical operator and the expressions  The && operator changes into ||  The || operator changes into &&  The ! is applied to both expressions  Remember, two not operators side by side cancel each other out so they can both be removed 29
  • 30. THE NOT OPERATOR  When exp1 and exp2 are simple logical expressions  !(exp1 && exp2) same as (!exp1 || !exp2)  !(exp1 || exp2) same as (!exp1 && !exp2)  !(!exp1 || !exp2) same as (!!exp1 && !!exp2) or (exp1 && exp2)  !(!exp1 && !exp2) same as (!!exp1 || !!exp2) or (exp1 || exp2)  Hence, there are many different ways to represent the same logical expression 30
  • 31. THE NOT OPERATOR  Examples with float variables x = 4.3 and y = 9.2  ((x < 5) && (y < 10)) is true  !((x < 5) && (y < 10)) is false  ( !(x < 5) || !(y < 10)) is false  ((x >= 5) || (y >= 10)) is false  !((x >= 5) || (y >= 10)) is true  ( !(x >= 5) && !(y >= 10)) is true  ((x < 5) && (y < 10)) is true 31
  • 32. SUMMARY  In this section, we have focused on how logical expressions can be written in C++  We have seen how relational operators (<, <=, >, >=, ==, and !=) can be used to create simple logical expressions  We have seen how logical operators (&& and !!) can be used to make more complex logical expressions  Finally, we have seen how the not operator (!) can be used to reverse the true/false value of logical expressions 32
  • 34. THE IF STATEMENT  Sometimes we want to selectively execute a block of code  The C++ syntax of the if statement is: if ( logical expression ) { //Block of code if expression is true statement1; statement2; }  When expression is true, the block of code is executed  When expression is false, the block of code is skipped 34
  • 35. THE IF STATEMENT Allows statements to be conditionally executed or skipped over Models the way we mentally evaluate situations:  "If it is raining, take an umbrella."  "If it is cold outside, wear a coat." 35
  • 38. THE IF STATEMENT The if statement has the following syntax: if ( condition ) statement; if is a C reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.
  • 39. THE IF STATEMENT  Programming style suggestions:  The block of code should be indented 3-4 spaces to aid program readability  If the block of code is only one line long the { } brackets can be omitted  Never put a semi-colon directly after the Boolean expression in an if statement  The empty statement between ) and ; will be selectively executed based on the logical expression value  The block of code directly below if statement will always be executed, which is probably not what you intended 39
  • 40. THE IF STATEMENT  We can visualize the program’s if statement decision process using a “flow chart” diagram 40 Logical expression Block of code true false
  • 41. THE IF STATEMENT  If the logical expression is true, we take one path through the diagram (executing the block of code) 41 Logical expression Block of code true false
  • 42. THE IF STATEMENT  If the logical expression is false, we take a different path through the diagram (skipping over the block of code) 42 Logical expression Block of code true false
  • 43. THE IF STATEMENT // Simple if statement int a, b; cin >> a >> b; if (a < b) cout << “A is smaller than Bn”; 43
  • 44. THE IF STATEMENT // One line block of code int a, b; cin >> a >> b; if (a == b) cout << “A is equal to Bn”; 44
  • 45. THE IF STATEMENT // Block of code that never executes if (1 == 2) cout << “This code will never executen”; 45
  • 46. THE IF STATEMENT // Block of code that always executes if (true) cout << “This code will always executen”; 46
  • 47. 47 IF SELECTION STRUCTURE Flowchart of pseudocode statement true false grade >= 60 print “Passed” A decision can be made on any expression. zero - false nonzero - true Example: 3, - 4 is true Translation into C++ If student’s grade is greater than or equal to 60 Print “Passed” if ( grade >= 60 ) cout << "Passed";
  • 48. WHAT IS THE OUTPUT? int m = 5; int n = 10; if (m < n) ++m; ++n; cout << " m = " << m << " n = " << n << endl;
  • 49. WHAT IS THE OUTPUT? int m = 10; int n = 5; if (m < n) ++m; ++n; cout << " m = " << m << " n = " << n << endl;
  • 50. THE IF-ELSE STATEMENT  Sometimes we need to handle two alternatives in our code  The C++ syntax of the if-else statement is: if ( logical expression ) { // Block of code to execute if expression is true } else { // Block of code to execute if expression is false } 50
  • 51. THE IF-ELSE STATEMENT An else clause can be added to an if statement to make an if- else statement if ( condition ) statement1; else statement2; • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed • One or the other will be executed, but not both
  • 52. THE IF-ELSE STATEMENT  Programming style suggestions:  Type the “if line” and the “else line” and the { } brackets so they are vertically aligned with each other  Do not put a semi-colon after the “if line” or the “else line” or you will get very strange run time errors  The two blocks of code should be indented 3-4 spaces to aid program readability  If either block of code is only one line long the { } brackets can be omitted 52
  • 53. THE IF-ELSE STATEMENT  We can visualize the program’s if-else statement decision process using a “flow chart” diagram 53 Logical expression Block of code executed if true true false Block of code executed if false
  • 54. THE IF-ELSE STATEMENT  If the logical expression is true, we take one path through the diagram (executing one block of code) 54 Logical expression Block of code executed if true true false Block of code executed if false
  • 55. THE IF-ELSE STATEMENT  If the logical expression is false, we take one path through the diagram (executing the other block of code) 55 Logical expression Block of code executed if true true false Block of code executed if false
  • 56. THE IF-ELSE STATEMENT // Simple if-else example if ((a > 0) && (b > 0)) { c = a / b; a = a - c; } else { c = a * b; a = b + c; } 56
  • 57. THE IF-ELSE STATEMENT // Ugly if-else example if (a < b) { c = a * 3; a = b - c; } else a = c + 5;  This code is nice and short but it is hard to read 57
  • 58. THE IF-ELSE STATEMENT // Pretty if-else example if (a < b) { c = a * 3; a = b - c; } else a = c + 5;  This code takes more lines but it is easier to read 58
  • 59. TESTING A SERIES OF CONDITIONS Use if … else … if sequences to test a series of conditions: If your score is over 90 your letter grade is A else if your score is over 80 your letter grade is B else your letter grade is C. 59
  • 60. GRADE CALCULATION EXAMPLE  How can we convert test scores to letter grades?  We are given numerical values between 0..100  We want to output A,B,C,D,F letter grades  We will want series of if-else statements  If test score between 90..100 output A  Else if score between 80..89 output B  Else if score between 70..79 output C  Else if score between 60..69 output D  Else if score between 0..59 output F 60
  • 61. GRADE CALCULATION EXAMPLE // Program to convert test scores into letter grades #include <iostream> using namespace std; int main() { // Local variable declarations // Read test score // Calculate grade // Print output return 0; } 61 The first step is to write comments in the main program to explain our approach
  • 62. GRADE CALCULATION EXAMPLE // Program to convert test scores into letter grades #include <iostream> using namespace std; int main() { // Local variable declarations float Score = 0; char Grade = '?' ; // Read test score cout << “Enter test score: “; cin >> Score; … 62 We add code to the main program to get the input test score
  • 63. GRADE CALCULATION EXAMPLE … // Local variable declarations float Score = 0; char Grade = '?' ; // Read test score cout << “Enter test score: “; cin >> Score; // Calculate grade if (Score >= 90) Grade = 'A'; // Print output cout << “Grade: ” << Grade; … 63 We add more code calculate one letter grade and print output
  • 64. GRADE CALCULATION EXAMPLE … // Calculate grade if (Score >= 90) Grade = 'A'; else if (Score >= 80) Grade = 'B'; else if (Score >= 70) Grade = 'C'; else if (Score >= 60) Grade = 'D'; else Grade = 'F'; … 64 We add more code to calculate the remaining letter grades Do you think there will be any issues if we use if instead of else if ????
  • 65. GRADE CALCULATION EXAMPLE  How should we test the grade calculation program?  Start with values we know are in the middle of the A,B,C,D,F letter ranges (e.g. 95,85,75,65,55)  Then test values “on the border” of the letter grade ranges to make sure we have our “>=“ and “>” conditions right (e.g. 79,80,81)  Then test values that are outside the 0..100 range to see what happens – is this what we want?  Finally, see what happens if the user enters something other than an integer value (e.g. 3.14159, “hello”) 65
  • 66. RANGE CHECKING Used to test to see if a value falls inside a range: if (grade >= 0 && grade <= 100) cout << "Valid grade"; Can also test to see if value falls outside of range: if (grade <= 0 || grade >= 100) cout << "Invalid grade"; Cannot use mathematical notation: if (0 <= grade <= 100) //doesn’t work! 66
  • 67. COMPARING CHARACTERS Characters are compared using their ASCII values 'A' < 'B'  The ASCII value of 'A' (65) is less than the ASCII value of 'B'(66) '1' < '2'  The ASCII value of '1' (49) is less than the ASCI value of '2' (50) Lowercase letters have higher ASCII codes than uppercase letters, so 'a' > 'Z' 67
  • 68. SUMMARY  In this section we have studied the syntax and use of the C++ if statement and the if-else statement  We have also seen how flow chart diagrams can be used to visualize different execution paths in a program  Finally, we showed how if statements can be used to implement a simple grade calculation program 68
  • 70. NESTED IF STATEMENTS We can have two or more if statements inside each other to check multiple conditions  These are called nested if statements Nested if statements can be used to test more than one condition Use indentation to reflect nesting and aid readability  Typically indent 3-4 spaces or one tab Need to take care when matching up { } brackets  This way you can decipher the nesting of conditions 70
  • 71. NESTED IF STATEMENTS if ( logical expression1 ) { if ( logical expression2 ) { // Statements to execute if expressions1 and expression2 are true } else { // Statements to execute if expression1 true and expression2 false } } else { // Statements to execute if expression1 false } 71
  • 72. FLOWCHART FOR A NESTED IF STATEMENT 72
  • 73. NESTED IF CODE // Determine loan qualification if (employed == ‘y’) { if (recentGrad == ‘y’) { cout << “You qualify!” } } Note: this could be done with one if and two conditions. 73
  • 74. NESTED IF STATEMENTS // Simple nested if example cin >> a >> b; if (a < b) { cout << “A is smaller than Bn”; if ((a > 0) && (b > 0)) cout << “A and B are both positiven”; else cout << “A or B or both are negativen”; } 74
  • 75. NESTED IF STATEMENTS // Ugly nested if example if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; }  It is hard to see what condition the else code goes with 75
  • 76. NESTED IF STATEMENTS // Pretty nested if example if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; } 76
  • 77. BOOLEAN VARIABLES  In C++ we can store true/false values in Boolean variables  The constants “true” and “false” can be used to initialize these variables  bool Done = true;  bool Quit = false;  Boolean expressions can also be used to initialize these variables  bool Positive = (a >= 0);  bool Negative = (b < 0); 77
  • 78. BOOLEAN VARIABLES  Boolean variables and true/false constants can also be used in logical expressions  (Done == true) is true  (Quit != true) is true  (Done == Quit) is false  (true == Positive) is true  ((a < b) == false) is false  (Negative) is false 78
  • 79. BOOLEAN VARIABLES  Internally C++ stores Boolean variables as integers  0 is normally used for false  1 is normally used for true  Any value != 1 is also considered true  It is considered “bad programming style” to use integers instead of true/false  bool Good = 0;  bool Bad = 1;  bool Ugly = a; 79
  • 80. BOOLEAN VARIABLES  Integers are used when writing Boolean values  cout << Good will print 0  cout << Bad will print 1  cout << Ugly will also print 1  Integers are also used when reading Boolean values  cin >> Good;  Entering 0 sets Good variable to false  Entering any value >= 1 sets Good variable to true  Entering value < 0 also sets Good variable to true 80
  • 81. PRIME NUMBER EXAMPLE  How can we test a number to see if it is prime?  We are given numerical values between 1..100  We need to see if it has any factors besides 1 and itself  We need some nested if statements  Test if input number is between 1..100  If so, then test if 2,3,5,7 are factors of input number  Then print out “prime” or “not prime” 81
  • 82. PRIME NUMBER EXAMPLE // Check for prime numbers using a factoring approach #include <iostream> using namespace std; int main() { // Local variable declarations // Read input parameters // Check input is valid // Check if number is prime // Print output return 0; } 82 For the first version of program we just write comments in the main program to explain our approach
  • 83. PRIME NUMBER EXAMPLE // Check for prime numbers using a factoring approach #include <iostream> using namespace std; int main() { // Local variable declarations int Number = 0; bool Prime = true; // Read input parameters cout << “Enter a number [1..100]:”; cin >> Number; 83 For the second version of program we initialize variables and read the input value from user
  • 84. PRIME NUMBER EXAMPLE … cout << “Enter a number [1..100]:”; cin >> Number; // Check input is valid if ((Number < 1) || (Number > 100)) cout << “Error: Number is out of rangen”; else { // Check if number is prime // Print output } 84 For the next version of the program we add code to verify the range of input value
  • 85. PRIME NUMBER EXAMPLE // Check if number is prime if (Number == 1) Prime = false; if ((Number > 2) && (Number % 2 == 0)) Prime = false; if ((Number > 3) && (Number % 3 == 0)) Prime = false; if ((Number > 5) && (Number % 5 == 0)) Prime = false; if ((Number > 7) && (Number % 7 == 0)) Prime = false; // Print output if (Prime) cout << “Number “ << Number << “ IS primen”; else cout << “Number “ << Number << “ is NOT primen”; 85 In the final version we finish the prime number calculation and print the output
  • 86. PRIME NUMBER EXAMPLE  How should we test the prime number program?  Test the range checking code by entering values “on the border” of the input range (e.g. 0,1,2 and 99,100,101)  Test program with several values we know are prime  Test program with several values we know are not prime  To be really compulsive we could test all values between 1..100 and compare to known prime numbers  What is wrong with this program?  It only works for inputs between 1..100  It will not “scale up” easily if we extend this input range 86
  • 87. SUMMARY  In this section we showed how if statements and if-else statements can be nested inside each other to create more complex paths through a program  We also showed how proper indenting is important to read and understand programs with nested if statements  We have seen how Boolean variables can be used to store true/false values in a program  Finally, we used an incremental approach to create a program for checking the factors of input numbers to see if they are prime or not 87
  • 88. EXAMPLE: WAGES.CPP Write a C++ program that calculates weekly wages for hourly employees.  Regular hours 0 - 40 are paid at $10/hours.  Overtime (> 40 hours per week) is paid at 150%
  • 90. SWITCH STATEMENTS  The switch statement is convenient for handling multiple branches based on the the value of one decision variable  The program looks at the value of the decision variable  The program jumps directly to the matching case label  The statements following the case label are executed  Special features of the switch statement:  The “break” command at the end of a block of statements will make the program jump to the end of the switch  The program executes the statements after the “default” label if no other cases match the decision variable 90
  • 91. SWITCH STATEMENTS switch ( decision variable ) { case value1 : // Statements to execute if variable equals value1 break; case value2: // Statements to execute if variable equals value2 break; ... default: // Statements to execute if variable not equal to any value } 91
  • 92. SWITCH STATEMENTS int Number = 0; cin >> Number; switch (Number) { case 0: cout << “This is nothing << endl; break; case 7: cout << “My favorite number” << endl; break; 92
  • 93. SWITCH STATEMENTS case 21: cout << “Lets go for a drink” << endl; break; case 42: cout << “The answer to the ultimate question” << endl; break; default: cout << “This number is boring” << endl; } 93
  • 94. SWITCH STATEMENTS  The main advantage of switch statement over a sequence of if-else statements is that it is much faster  Jumping to blocks of code is based on a lookup table instead of a sequence of variable comparisons  The main disadvantage of switch statements is that the decision variable must be an integer (or a character)  We can not use a switch with a float or string decision variable or with complex logical expressions 94
  • 95. MENU EXAMPLE  How can we create a user interface for banking?  Assume user selects commands from a menu  We need to see read and process user commands  We can use a switch statements to handle menu  Ask user for numerical code for user command  Jump to the code to process that banking operation  Repeat until the user quits the application 95
  • 96. MENU EXAMPLE // Simulate bank deposits and withdrawals #include <iostream> using namespace std; int main() { // Local variable declarations // Print command prompt // Read user input // Handle banking command return 0; } 96 For the first version of program we just write comments in the main program to explain our approach
  • 97. MENU EXAMPLE … // Local variable declarations int Command = 0; // Print command prompt cout << “Enter command number:n”; // Read user input cin >> Command; … 97 For the next version of program we add the code to read the user command
  • 98. MENU EXAMPLE // Handle banking command switch (Command) { case 0: // Quit code break; case 1: // Deposit code break; case 2: // Withdraw code break; case 3: // Print balance code break; } 98 Then we add the skeleton of the switch statement to handle the user command
  • 99. MENU EXAMPLE // Simulate bank deposits and withdrawals #include <iostream> using namespace std; int main() { // Local variable declarations int Command = 0; int Money = 0; int Balance = 100; // Print command prompt cout << “Enter command number:n” << “ 0 - quitn” << “ 1 - deposit moneyn” << “ 2 - withdraw moneyn” << “ 3 - print balancen”; 99 In the final version add bank account variables and add code to perform banking operations
  • 100. MENU EXAMPLE // Read and handle banking commands cin >> Command; switch (Command) { case 0: // Quit code cout << “See you later!” << endl; break; case 1: // Deposit code cout << “Enter deposit amount: “; cin >> Money; Balance = Balance + Money; break; 100
  • 101. MENU EXAMPLE case 2: // Withdraw code cout << “Enter withdraw amount: “; cin >> Money; Balance = Balance - Money; break; case 3: // Print balance code cout << “Current balance = “ << Balance << endl; break; default: // Handle other values cout << “Ooops try again” << endl; break; } // Print final balance cout << “Final balance = “ << Balance << endl; } 101
  • 102. MENU EXAMPLE  How should we test this program?  Test the code by entering all valid menu commands  What happens if we enter an invalid menu command?  What happens if we enter an invalid deposit or withdraw amount (e.g. negative input values)?  What is wrong with this program?  We might end up with a negative account balance  There is only one bank account and zero security 102
  • 103. SOFTWARE ENGINEERING TIPS  There are many ways to write conditional code  Your task is to find the simplest correct code for the task  Make your code easy to read and understand  Indent your program to reflect the nesting of blocks of code  Develop your program incrementally  Compile and run your code frequently  Anticipate potential user input errors  Check for normal and abnormal input values 103
  • 104. SOFTWARE ENGINEERING TIPS  Common programming mistakes  Missing or unmatched ( ) brackets in logical expressions  Missing or unmatched { } brackets in conditional statement  Missing break statement at bottom of switch cases  Never use & instead of && in logical expressions  Never use | instead of || in logical expressions  Never use = instead of == in logical expressions  Never use “;” directly after logical expression 104
  • 105. SUMMARY  In this section we have studied the syntax and use of the C++ switch statement  We also showed an example where a switch statement was used to create a menu-based banking program  Finally, have discussed several software engineering tips for creating and debugging conditional programs 105

Editor's Notes

  1. A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself. However, 4 is composite because it is a product (2 × 2) in which both numbers are smaller than 4. Primes are central in number theory because of the fundamental theorem of arithmetic: every natural number greater than 1 is either a prime itself or can be factorized as a product of primes that is unique up to their order.