CS102 Introduction to Computer Programming

Download Report

Transcript CS102 Introduction to Computer Programming

CS102
Introduction to Computer
Programming
Chapter 4 Making Decisions
Continued
Chapter 4 Topics
•
•
•
•
•
•
•
•
•
•
Menus
Nested if Statements
Logical Operators
Checking Numeric Ranges
Validating User Input
More variable Declarations and Scope
Variables with the same names
Comparing Strings
The Conditional Operator
The switch
Menus
• A menu is a list of alternative actions from which
the user can select
– The user makes a decision and the program acts on it
– The if/else if statement determines what the decision is
from a list of valid decisions
• Menus can both document the programs functions
as well as direct their execution
Concept - You can use the if/else if statement to create menu
driven programs
Program 4-14
// This program displays a menu and asks the
user to make a
// selection. An if/else if statement determines
which item
// the user has chosen.
#include <iostream.h>
void main(void)
{
int Choice, Months;
float Charges;
cout << "\t\tHealth Club Membership
Menu\n\n";
cout << "1. Standard Adult
Membership\n";
cout << "2. Child Membership\n";
cout << "3. Senior Citizen Membership\n";
cout << "4. Quit the Program\n\n";
cout << "Enter your choice: ";
cin >> Choice;
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
if (Choice == 1)
{
cout << "\nFor how many
months? ";
cin >> Months;
Charges = Months * 40.00;
cout << "The total charges are $"
<< Charges << endl;
}
Program continues
else if (Choice == 2)
{
cout << "\nFor how many months?
";
cin >> Months;
Charges = Months * 20.00;
cout << "The total charges are $" <<
Charges << endl;
}
else if (Choice == 3)
{
cout << "\nFor how many months?
";
cin >> Months;
Charges = Months * 30.00;
cout << "The total charges are $" <<
Charges << endl;
}
else if (Choice != 4)
{
cout << "The valid
choices are 1 through 4.
Run the\n";
cout << "program again
and select one of
those.\n";
}
}
Program Output
Health Club Membership Menu
1. Standard Adult Membership
2. Child Membership
3. Senior Citizen Membership
4. Quit the Program
Enter your choice: 3 [Enter]
For how many months? 6 [Enter]
The total charges are $180.00
Nested if Statements
• All the conditions of a nested if must be true for
the conditional code to execute.
• Use proper indentation to help keep track of what
else belongs to what if
Concept - A nested if statement is an if statement in the
conditionally executed code of another if statement
Flow chart for nested if
if
expression
True
False
if
expression
False
end
True
Statement
or block
Program 4-15
// This program demonstrates the nested if
statement.
#include <iostream.h>
void main(void)
{
char Employed, RecentGrad;
cout << "Answer the following
questions\n";
cout << "with either Y for Yes or ";
cout << "N for No.\n";
cout << "Are you employed? ";
cin >> Employed;
cout << "Have you graduated from
college ";
cout << "in the past two years? ";
cin >> RecentGrad;
if (Employed == 'Y')
{
if (RecentGrad == 'Y')
{
cout << "You qualify for the
special ";
cout << "interest rate.\n";
}
}
}
Program Output
Answer the following questions
with either Y for Yes or N for No.
Are you employed? Y
Have you graduated from college in the
past two years? Y
You qualify for the special interest rate.
Logical Operators
• &&
their
• ||
and
• !
Not
or
if both sub-expressions are true
connection is true
if either sub-expression is true the
connection is true
Reverses the truth of an
expression
Concept - Logical operators connect two or more relational
expressions into one or reverse the logic of an expression
Truth Table for Logical Operators
And
&&
exp 1 True
exp 1 False
exp 2
True
T
F
Or
||
exp 1 True
exp 1 False
T
T
Not
!
exp 2
False
F
F
T
F
exp True = = False(0)
exp False = = True(1)
Program 4-17
/* This program demonstrates the &&
logical operator.*/
#include <iostream.h>
void main(void)
{
char Employed, RecentGrad;
cout << "Answer the following
questions\n";
cout << "with either Y for Yes or ";
cout << "N for No.\n";
cout << "Are you employed? ";
cin >> Employed;
cout << "Have you graduated from
college ";
cout << "in the past two years? ";
cin >> RecentGrad;
if (Employed == 'Y'&&
RecentGrad == 'Y')
{
cout << "You qualify for the
special ";
cout << "interest rate.\n";
}
else
{
cout << "You must be
employed and have \n";
cout << "graduated from
college in the\n";
cout << "past two years to
qualify.\n";
}
}
Program Output
Answer the following questions
with either Y for Yes or
N for No.
Are you employed? Y
Have you graduated from college in the past two
years? N
You must be employed and have
graduated from college in the
past two years to qualify.
Program 4-18
/* This program asks the user for their
annual income and the number of years
they have been employed at their
current job. The || operator is used in a
if statement that determines if the
income is at least $35,000 or their time
on the job is more than 5 years.*/
#include <iostream.h>
void main(void)
{
float Income;
int Years;
cout << "What is your annual
income? ";
cin >> Income;
cout << "How many years have you
worked at "
<< "your current job? ";
cin >> Years;
if (Income >= 35000 || Years > 5)
cout << "You qualify.\n";
else
{
cout << "You must earn at
least $35,000 or have\n";
cout << "been employed for more
than 5 years.\n";
}
}
Program Output
What is your annual income? 40000 [Enter]
How many years have you worked at your
current job? 2 [Enter]
You qualify.
Program Output
What is your annual income? 20000 [Enter]
How many years have you worked at your
current job? 7 [Enter]
You qualify.
Program 4-19
#include <iostream.h>
void main(void)
{
float Income; int Years;
cout << "What is your annual income? ";
cin >> Income;
cout << "How many years have you worked at "
<< "your current job? ";
cin >> Years;
//(Income >= 35000 || Years > 5)
if (!(Income >= 35000 || Years > 5))
{
cout << "You must earn at least $35,000 or have\n";
cout << "been employed for more than 5 years.\n";
}
else
cout << "You qualify.\n";
}
Precedence of Logical Operators
!
&&
||
4.11 Checking Numeric Ranges
With Logical Operators
• Logical operators are effective for
determining if a number is in or out of
a range.
Checking Numeric Ranges
• Use && to check if values are inside of a range
if ( value > = low end && value < = high end)
cout << "The value is inside the range";
• Use || to check if values are outside of a range
if ( value< = low end || value > = high end)
cout << "The value is outside the range";
Concept - Logical operators are effective for checking if a
number is in or out of a range
Examples of validation:
• Numbers are checked to ensure they are within a
range of possible values.
• Values are checked for their “reasonableness”.
• Items selected from a menu or other set of choices
are checked to ensure they are available options.
• Variables are checked for values that might cause
problems, such as division by zero.
Validating User Input
• Range checking - the temperature of liquid water
should be between 32oF and 212oF
• Reasonableness checking - there are only 168
hours in a week
• Acceptable menu selection - is the input one of the
menu options
• Useable inputs - divide by zero
Concept - Garbage in equals garbage out. Write programs to
filter out bad data
Program 4-21A
#include <iostream.h>
void main(void)
{
cout << "What is your annual
income? ";
float Income;
cin >> Income;
cout << "How many years have
you worked at "
<< "your current job? ";
int Years;
}
cin >> Years;
if (Income >= 35000 || Years >5)
cout << "You qualify.\n";
else
{
cout << "You must earn at
least $35,000 or
have\n";
cout << "been employed for
more than 5 years.\n";
}
Program 4-22
// This program demonstrates a variable
declared in an inner block.
#include <iostream.h>
void main(void)
{
cout << "What is your annual income?
";
float Income;
cin >> Income;
if (Income >= 35000)
{
int Years;
cout << "How many years have
you worked at your
current job? ";
cin >> Years;
if (Years > 5)
cout << "You qualify.\n";
else
{
cout << "You must have been
employed for\n";
cout << "more than 5 years to
qualify.\n";
}
}
else
{
cout << "You must earn at least
$35,000 to\n";
cout << "qualify.\n";
}
More variable Declarations and
Scope
• Braces { } are used to signify a block of code.
– A variable can only be used within the block in which it
is declared
– This is referred to as local scope or block scope
Concept - The scope of a variable is limited to the block of code
in which it is declared
Variables with the same names
• If one block of code is nested within another it can
declare variables with the same names as those in
the outer block
– The variable will only exist wile the code in that block
is executing
– the variables in the outer block won't be useable until
the inner block is exited
Concept - A variable declared in an inner block can have the
same name as a variable declared in an outer block
Program 4-23
// This program uses two variables with the
name Number.
#include <iostream.h>
void main(void)
{
int Number;
cout << "Now enter
another number: ";
cin >> Number;
cout << "The second
number you
entered was ";
cout << Number << endl;
}
cout << "Your first number was "
<< Number << endl;
cout << "Enter a number greater than 0: }
";
Program Output
cin >> Number;
Enter a number greater than 0: 2 [Enter]
if (Number > 0)
Now enter another number: 7[Enter]
The second number you entered was 7
{
Your first number was 2
int Number;
Comparing Strings
• The strcmp function is used to compare character
strings
strcmp(string1, string2)
returns 1 if string1 is alphabetically higher
returns -1 if string2 alphabetically higher
returns 0 if both strings are identical
• #include <string> is required to use strcmp
Concept - Character strings can not be compared using
relational operators.
Sorting Strings
If (strcmp(string1,string2)) < 0)
cout <<string1<<"\n" <<string2;
else
cout << string2<<"\n" <<string1;
Concept - The strcmp function can be used to alphabetically
sort character strings
The Conditional Operator
• The conditional operator is a ternary operator
expression1 ? expresson2 : espression3
if (expression1)
expression2;
else
expression3;
Concept - The conditional operator can be used to create short
expressions that work like if/else statements
The switch
• The switch statement test the value of an integer
expression and then uses the value to determine
which block of code to branch to
switch (integer expression)
{
case result1: constant expression: one or more statements;
break;
case result2: constant expression: one or more statements;
break;
default: statement; (optional)
}
Concept - The switch statement lets the value of a variable or
expression determine where the program will branch to
Switch Flow
Chart
if
Case
True
Statement
or block
False
False
if
Case
True
if
break
True
Statement
or block
False
False
Default
end
if
break
True
The switch statement
• The expressions in case statements must be
unique
• The default statement is optional
• A break is not needed after the last
statement
• The switch statement is a natural for
building menus
Program 4-31
/* The switch statement in this program
tells the user something he or she
already knows: what they just entered!
*/
#include <iostream.h>
void main(void)
{
char Choice;
cout << "Enter A, B, or C: ";
cin >> Choice;
switch (Choice)
{
case 'A': cout << "You entered A.\n";
break;
case 'B': cout << "You entered B.\n";
break;
case 'C': cout << "You entered C.\n";
break;
default: cout << "You did not enter A,
B, or C!\n";
}
}
Program Output
Enter A, B, or C: B [Enter]
You entered B.
Program Output
Enter a A, B, or C: F [Enter]
You did not enter A, B, or C!
Program 4-32
/* The switch statement in this program tells
the user something he or she already
knows: what they just entered!
*/
#include <iostream.h>
void main(void)
{
char Choice;
cout << "Enter A, B, or C: ";
cin >> Choice;
switch (Choice)
{
case 'A': cout << "You entered A.\n";
case 'B': cout << "You entered B.\n";
case 'C': cout << "You entered C.\n";
default: cout << "You did not enter A, B,
or C!\n";
}
}
Program Output
Enter a A, B, or C: A [Enter]
You entered A.
You entered B.
You entered C.
You did not enter A, B, or C!
Program Output
Enter a A, B, or C: C [Enter]
You entered C.
You did not enter A, B, or C!
Program 4-33
/* This program is carefully constructed to
use the "fallthrough" feature of the
switch statement.
*/
#include <iostream.h>
void main(void)
{
int ModelNum;
cout << "Our TVs come in three
models:\n";
cout << "The 100, 200, and 300. Which
do you want? ";
cin >> ModelNum;
cout << "That model has the following
features:\n";
switch (ModelNum)
{
case 300:cout << "\tPicture-ina-picture.\n";
case 200:cout << "\tStereo
sound.\n";
case 100:cout << "\tRemote
control.\n";
break;
default:cout << "You can only
choose the 100,";
cout << "200, or
300.\n";
}
}
Program Output with Example Input
Our TVs come in three models:
The 100, 200, and 300. Which do you want? 100 [Enter]
That model has the following features:
Remote control.
Program Output with Example Input
Our TVs come in three models:
The 100, 200, and 300. Which do you want? 200 [Enter]
That model has the following features:
Stereo sound.
Remote control.
Program 4-34
/*The switch statement in this program
uses the "fallthrough“ feature to catch
both upper and lowercase letters
entered by the user.
*/
#include <iostream.h>
void main(void)
{
char FeedGrade;
cout << "Our dog food is available in
three grades:\n";
cout << "A, B, and C. Which do you
want pricing for? ";
cin >> FeedGrade;
switch(FeedGrade)
{
case 'a':
case 'A': cout << "30 cents per
pound.\n";
break;
case 'b':
case 'B': cout << "20 cents per
pound.\n";
break;
case 'c':
case 'C': cout << "15 cents per
pound.\n";
break;
default: cout << "That is an
invalid choice.\n";
}
}