# Topic04 If Else Switch

### Pages to are hidden for

"Topic04 If Else Switch"

```					      Selection Structures:
O
O   if and switch Statements
P
Professor: Aishy Amer
COEN243 Topic 04

Control   Structures
Logical  Expressions
Introduction to the if Dependent Control Statement

if Statements with Compound Alternatives

Decision Steps in Algorithms

Checking the Correctness of an Algorithm

Nested if Statements and Multiple Alternative Decisions

The switch Control Statement

Common Programming Errors
O             Selection Statements
O
P
    Selection statements are statements that allow
alternatives to straight sequential processing
    In particular:
– if statements (do this only if a condition is true)
– if-else statements (do either this or that)
– Logical expressions (evaluate to true or false)
– Boolean operators (not: ! and: && or: ||)

2
O                                  Motivation
O
P
int main() {

float A,B,C,delta, root1, root2;

cout << "Enter your Quad. Eq.: enter 3 real values for a,b,c."<<endl;

cin>> A >> B >> C;

if(A != 0.0) {

delta = B*B - 4*A*C ;

if(delta < 0)      {

cout << "Your A,B,C result in complex roots."<< endl;

}

else     {

root1 = -B/(2*A) + sqrt(delta)/(2*A);

root2 = -B/(2*A) - sqrt(delta)/(2*A);

cout << "root1 is: " << root1 << endl;

cout << "root2 is: " << root2 << endl;

} // end of if(delta ..)

} // end of if(A != 0

else {

cout << "A is ZERO. Re-Run."<< endl;

}

return 0;

}
3
O            4.1 Control Structures
O
P
– Programs must often anticipate a variety of
situations.
– Consider an Automated Teller Machine:
• Requests:
– ATMs must serve valid bank customers.
– ATMs must also reject invalid PINs.
• The program (code that controls an ATM must permit
these different requests.
• Software developers must implement code that
anticipates all possible transactions.

4
O           4.2 Logical Expressions
O
P

Declaration
int month = 9;
Expression         is
(month > 9)        False
(month < 9)        False
(month >= 9)       True
(month <= 9)       True

5
O             Boolean Variables
O
P

   Data type: bool
   Predefined (with C++ compiler)

bool      leapYear;

leapYear = true;       // Non zero return value
leapYear = false;      // Zero return value

6
O           Boolean Expressions
O
P

Examples (Write T for True, or F for False):
int n1 = 55;
int n2 = 75;
n1 < n2           // _____

n1 > n2           // _____

(n1 + 35) > n2    // _____

(n1-n2) < 0.1     // _____

n1 == n2          // _____

7
O             Logical Expressions
O
P
– Logical expressions often use these relational
operators:

>    Greater than
<    Less than
>=   Greater than or equal
<=   Less than or equal
==   Equal
!=   Not equal

8
O             Logical Operators
O
P

   Logical operator (&& means AND) used
in an if...else statement:
( (tryIt >= 0) && (tryIt <= 100) )

   Logical operator (| | means OR) used in
an if...else statement:
( (tryIt >= 0) | | (tryIt <= 100) )

9
O           Using &&
O
P

 Assume tryIt = 90;
 Is tryIt within the range of 0 and 100 ?

( (tryIt >= 0) && (tryIt <= 100) )
( ( 90 >= 0) && ( 90 <= 100) )
(       1      &&           1   )
1

10
O           Using &&
O
P

 Assume tryIt = 99;
 Is tryIt outside the range of 0 and 100 ?

( (tryIt < 0) ¦¦ (tryIt > 100) )
( ( 99 < 0) ¦¦ ( 99 > 100) )
(    0 ¦¦        0    )
0

11
O       Truth Tables for Boolean
O
P Operators

   Truth tables for logical operators !, ¦¦, &&
– 1 is a symbol for true
– 0 is a symbol for false

Operation   Result   Operation   Result   Operation   Result
! 0         1        1 ¦¦ 1      1        1 && 1      1
! 1         0        1 ¦¦ 0      1        1 && 0      0
0 ¦¦ 1      1        0 && 1      0
0 ¦¦ 0      0        0 && 0      0

12
O               Precedence of Operators
O
P

   Precedence: most operators are evaluated
(grouped) in a left-to-right order:
– a / b / c / d is equivalent to (((a/b)/c)/d)
   Assignment operators group in a right-to-left
order so the expression
–    x = y = z = 0.0
is equivalent to
(x=(y=(z=0.0)))

13
O                Precedence of Operators
O
P

Operator    Description               Grouping
Highest          ::          Scope resolution          Left to right
()          Function call
Unary            !,   +, -   Not, unary plus/minus     Right to left
Multiplicative   *    / %    Multipy/divide/remainder Left to right
Additive         +     -     Binary plus, minus       Left to right
Input/Output     >>     <<   Extraction / insertion    Left to right
Relational       <    >      Less/Greater than         Left to right
<=   >=     Less/Greater or equal
Equality         ==    !=    Equal, Not equal          Left to right
and              &&          Logical and               Left to right
or               ¦¦          Logical or                Left to right
Assignment       =           Assign expression         Right to left

14
O           Boolean Assignment
O
P

bool same; // declaration
same = true; //assignment

Form:
variable = expression;
Example:
same = (x = = y);

15
O       4.3 Introduction to the if
O
P Dependent Control Statement
– The if is the first statement that alters strict
sequential control.
– General form
if ( logical-expression )
true-part ;
– logical-expression: any expression that evaluates
to nonzero (true) or zero (false).
• In C++, almost everything is true or false.

16
O       if Control Statements
O
P with Two Alternatives

– The logical expression is evaluated.
– When true, the true-part is executed and the false-part
is disregarded.
– When the logical expression is false, the false-part
executes.
– General Form
if ( logical-expression )
true-part ;
else
false-part ;
17
O       What happens when an if
O
P statement executes?

gross          False
>100.0

True      net=gross-tax            net=gross

• After the logical expression of the if statement
evaluates, the true-part executes only if the logical
expression was true.

18
O             Programming Tip
O
P
   Using = for == is a common mistake.
   For example the following statements are legal:
    int x = 25;
   Because assignment statements evaluate to the
expression on the right of =
x = 1 is always 1, which is nonzero, that is true:
if (x = 1) // should be (x == 1)

19
O       4.4 if Statements with Compound
O
P Alternatives
– General form (also known as a block):
{
statement-1 ;
statement-2 ;
...
statement-N ;
}
– The compound statement groups together many
statements that are treated as one.

20
O            Writing Compound Statements
O
P
if (transactionType == 'c')
{ // process check
cout << "Check for \$" <<
transactionAmount << endl;
balance = balance - transactionAmount;
}
else
{ // process deposit
cout << "Deposit of \$" <<
transactionAmount << endl;
balance = balance + transactionAmount;
}
21
O            4.5 Decision Steps in Algorithms
O
P

   Algorithm steps that select from a choice of
actions are called decision steps
   The algorithm in the following case contains
decisions steps to compute an employee’s
gross and net pay after deductions
    The decision steps are coded as if statements

22
O      Decision Steps in Algorithms
O Payroll Case Study - Statement
P
   Your company pays its hourly workers once a week
   An employee’s pay is based upon the number of
hours worked (to the nearest half hour) and the
employee’s hourly pay rate
    Weekly hours exceeding 40 are paid at a rate of time
and a half
    Employees who earn over \$100 a week must pay
union dues of \$15 per week
   Write a payroll program that will determine the gross
pay and net pay for an employee
23
O      Decision Steps in Algorithms
O Payroll Case Study - Analysis
P
   The problem data include the input data for hours
worked and hourly pay and two required outputs, gross
pay and net pay
   There are also several constants: the union dues (\$15),
the minimum weekly earnings before dues must be paid
(\$100), the maximum hours before overtime must be
paid (40), and the overtime rate (1.5 times the usual
hourly rate)
   With this information, we can begin to write the data
requirements for this problem
   We can model all data using the money (see Section 3.7)
and float data types                        24
O      Decision Steps in Algorithms
O Payroll Case Study -Program Design
P
   The problem solution requires that the program read the
hours worked and the hourly rate before performing any
computations
   After reading these data, we need to compute and then
display the gross pay and net pay
   The structure chart for this problem (Fig. 4.6) shows the
decomposition of the original problem into five
subproblems
   We will write three of the subproblems as functions. For
these three subproblems, the corresponding function
name appears under its box in the structure chart
25
O      Decision Steps in Algorithms
O Payroll Case Study
P
– Display user instructions
(function instructUser)
– Enter hours worked and hourly rate
– Compute gross pay (function computeGross)
– Compute net pay (function computeNet)
– Display gross pay and net pay

26
O           money.h: example
O
P
void computeGross (float hours, float rate)
{
if (hours > MAX_NO_OVERTIME)
{
regularPay = ....;
overtimePay = ....;
gross = regularPay + overtimePay; // add
}
else
gross = hours * rate; //multiply
cout << gross; // use the << op.
}

27
O             PayrollFunctions.cpp
O
P
//   File: payrollFunctions.cpp
//   Computes and displays gross pay and net pay
//   given an hourly rate and number of hours
//   worked. Deducts union dues of \$15 if gross
//   salary exceeds \$100; otherwise, deducts no
//   dues.

#include <iostream>
using namespace std;

28
O           PayrollFunctions.cpp
O
P

// Functions used ...
void instructUser();
float computeGross(float, float);
float computeNet(float);
const float MAX_NO_DUES = 100.00;
const float dues = 15.00;
const float MAX_NO_OVERTIME = 40.0;
const float OVERTIME_RATE = 1.5;

29
O            PayrollFunctions.cpp
O
P
int main   ()
{
float   hours;
float   rate;
float   gross;
float   net;

// Display user instructions.
instructUser();

30
O            PayrollFunctions.cpp
O
P
// Enter hours and rate.
cout << "Hours worked: ";
cin >> hours;
cout << "Hourly rate: ";
cin >> rate;

// Compute gross salary.
gross = computeGross(hours, rate);

// Compute net salary.
net = computeNet(gross);

31
O            PayrollFunctions.cpp
O
P

// Print gross and net.
cout << "Gross salary is " << gross << endl;
cout << "Net salary is " << net << endl;

return 0;
}

32
O           PayrollFunctions.cpp
O
P
// Displays user instructions
void instructUser()
{
cout <<
"This program computes gross and net salary." << endl;
cout << "A dues amount of " << dues << " is deducted
for" << endl;
cout << "an employee who earns more than " <<
MAX_NO_DUES << endl << endl;
cout << "Overtime is paid at the rate of " <<
OVERTIME_RATE << endl;

33
O           PayrollFunctions.cpp
O
P
cout << "times the regular rate for hours worked over "
<< MAX_NO_OVERTIME << endl << endl;
cout << "Enter hours worked and hourly rate" << endl;
cout << "on separate lines after the prompts. " << endl;
cout << "Press <return> after typing each number." <<
endl << endl;
} // end instructUser

34
O            PayrollFunctions.cpp
O
P
// FIND THE GROSS PAY
float computeGross (float hours,      float rate)
{
// Local data ...
float gross;
float regularPay;
float overtimePay;

// Compute gross pay.
if (hours > MAX_NO_OVERTIME)
{
regularPay = MAX_NO_OVERTIME * rate;

35
O            PayrollFunctions.cpp
O
P
overtimePay = (hours - MAX_NO_OVERTIME) *
OVERTIME_RATE * rate;
gross = regularPay + overtimePay;
}
else
gross = hours * rate;

return gross;
}   // end computeGross

36
O            PayrollFunctions.cpp
O
P
// Find the net pay
float computeNet (float gross)
{
float net;

// Compute net pay.
if (gross > MAX_NO_DUES)
net = gross - dues;
else
net = gross;

return net;
}   // end computeNet
37
O            Payroll.cpp
O
P

Program output
This program computes gross and net salary.
A dues amount of \$15.00 is deducted for an
employee who earns more than \$100.00

Overtime is paid at the rate of 1.5 times the
regular rate on hours worked over 40
Enter hours worked and hourly rate on separate
lines after the prompts. Press <return> after
typing each number.
38
O           Payroll.cpp
O
P

Program output

Hours worked: 50
Hourly rate: 6
Gross salary is \$330.00
Net salary is \$315.00

39
O       4.6 Checking the Correctness of
O
P an Algorithm

   Verifying the correctness of an algorithm is a
critical step in algorithm design and often
saves hours of coding and testing time.

   We will now trace the execution of the refined
algorithm for the payroll problem solved in
the last section.

40
O       Checking the Correctness of an
O
P Algorithm
1. Display user instructions.
2. Enter hours worked and hourly rate.
3. Compute gross pay.
3.1. If the hours worked exceed 40.0 (max hours
before overtime)
3.1.1. Compute regularPay.
3.1.2. Compute overtimePay.
3.1.3. Add regularPay to overtimePay to get gross.
else

41
O       Checking the Correctness of an
O
P Algorithm
3.1.4. Compute gross as hours * rate.
4. Compute net pay.
4.1. If gross is larger than \$100.00
4.1.1. Deduct the dues of \$15.00 from gross pay.
else
4.1.2. Deduct no dues.
5. Display gross and net pay.

42
O       4.7 Nested if Statements and
O
P Multiple Alternative Decisions

   Nested logic is one control structure
containing another similar control
structure.

   An if...else inside another if...else. e.g.
(the 2nd if is placed on the same line as
the 1st):
43
O            Example of nested logic
O
P

if(x > 0)
numPos = numPos + 1;
else
if(x < 0)
numNeg = NumNeg + 1;
else
numZero = numZero + 1;

44
O               Example of nested logic
O
P
X        numPos     numNeg      numZero
3.0      _______    _______     _______
-3.6     _______    _______     _______
4.0      _______    _______     _______

Assume all variables initialized to 0

45
O      Writing a Nested if as a Multiple-
O Alternative Decision
P

   Nested if statements can become quite
complex.

    If there are more than three alternatives
and indentation is not consistent, it may
be difficult to determine the logical
structure of the if statement.

46
O
P
void displayGrade ( int score)
{
if (score >= 90)
cout << "Grade is A " << endl;
else if (score >= 80)
cout << "Grade is B " << endl;
else if (score >= 70)
cout << "Grade is C " << endl;
else if (score >= 60)
cout << "Grade is D " << endl;
else
cout << "Grade is F " << endl;
}                                       47
O           Order of Conditions
O
P

if (score >= 60)
cout << "Grade is D " << endl;
else if (score >= 70)
cout << "Grade is C " << endl;
else if (score >= 80)
cout << "Grade is B " << endl;
else if (score >= 90)
cout << "Grade is A " << endl;
else
cout << "Grade is F " << endl;
48
O           Short Circuit Evaluation
O
P

(single == ‘y’ && gender == ‘m’ && age >= 18)
– If single is false, gender and age
are not evaluated

(single == ‘y’ || gender == ‘m’ || age >= 18)
– If single is true, gender and age
are not evaluated

49
O       4.8 The switch Control
O
P Statement

switch ( switch-expression )
{
case value-1 :
statement(s)-1
break ; ... // many cases are allowed
case value-n :
statement(s)-n
break ;
default :
default-statement(s)
}
50
O            Switch Control
O
P

– When a switch statement is encountered,
the switch-expression is evaluated.
– This value is compared to each case value
until switch-expression == case value.
– All statements after the colon : are executed
– It is important to include the break
statement

51
O           Example switch Statement:
O
P

switch(watts) // Assume char option = '?’
{
case 25:
cout << " Life expectancy is 2500 hours. " << endl;
break;
case 40:
case 60:
cout << " Life expectancy is 1000 hours. " << endl;
break;
52
O            Example switch Statement
O
P
case 75:
case 100:
cout << " Life expectancy is 750 hours. " <<
endl;
break;
default: cout << "Invalid Bulb !!" << endl;
} // end switch

53
O            Trace the previous switch
O
P

– Show output when
• watts = '?'     ____________?
• watts = ’40’    ____________?
• watts = ’10'    ____________?
• watts = ’200'   ____________?
• watts = ’100'   ____________?

54
O       4.9 Common Programming
O
P Errors

   Failing to use { and }
// The true-part is the first cout only
cout <<"You receive an A !!!";
cout <<"You made it by " << (Grade-3.5) << "
points";
else <<<< Error >>>>

55
O             Common Programming Errors
O
P
   There are no compile time errors next, but there is an
intent error.
else
cout << "Sorry, you missed an A. ";
cout << "You missed it by " << 3.5-Grade << " points";
   With the above false part, you could get this
confusing output (when Grade = 3.9):
You received an A !!!.
You made it by 0.4 points.You missed it by -0.4 points

56
O           Corrected Version:
O
P

{
cout << "You received an A !!! " << endl;
cout << "You made it by " << (Grade-3.5) << " points";
// Do other things if desired
}
else
{
cout << " You did NOT receive an A !!! ";
cout << "You missed it by " << (3.5-Grade) <<" points";
}                                            57

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 4 posted: 8/7/2012 language: English pages: 57