presented by joaquin vila prepared by sally scott acs 168 problem solving using the computer week 12...
TRANSCRIPT
Presented byPresented by
Joaquin VilaJoaquin Vila
Prepared byPrepared by
Sally ScottSally Scott
ACS 168ACS 168Problem Solving Using the ComputerProblem Solving Using the Computer
ACS 168ACS 168Problem Solving Using the ComputerProblem Solving Using the Computer
Week 12
Boolean Expressions, Switches, For-Loops
Chapter 7
Week 12
Boolean Expressions, Switches, For-Loops
Chapter 7
Boolean Expressions
Either true or false Use relational operations
==, < , >, <= , >= , !=, &&, || type bool
can declare variables that have values of true or false
Evaluation of Boolean Expressions
Truth tables
ANDExp1 Exp2 Exp1&&Exp2 T T T T F F F T F F F F
ORExp1 Exp2 Exp1||Exp2 T T T T F T F T T F F F
NOTExp !(Exp) T F F T
Precedence Rules Unary operators: +, -, ++, --, !Binary operators *, /, %Binary operators +, -Boolean operators: <, >, <=, >=Boolean operators: ==, !=Boolean operator: &&Boolean operator: ||
low
high
How expressions are evaluated Evaluation
Leftmost expression evaluated first Others only as needed Consider:
1. a < b && b != c where a = 12, b = 6, c = 8
2. if ((j > 0) && (k/(j +1) > 10)) where j = -1
Integers as boolean values True converts to 1 False converts to 0 Any non-zero integer is true Consider:
if (!time > limit) where time = 36 and limit = 60
Given: a = 12, b = 6, c = 8
1. (!(a < b) && !(b > c))
2. ((a > b) && (a > c) || (b > c))
Given: x = 5, y = 3, z = 8: 1. x < 15 && !y < 0
2. x > z || y < z
3. x < y < z
4. x = y < z
5. x < y && y < z
Functions that return a Boolean Value
Can be used in if-else statementif (((rate >= 10) && (rate < 20)) || (rate == 0)){ …}
better way:if (appropriate(rate)) { …}
bool appropriate (int rate){ … if (((rate >= 10) && (rate < 20)) || (rate == 0)) …}
Nested if statementsif (expression) statement if true;else if (expression) statement if true; else statement if false;
if (expression) statement if true;else if (expression) statement if true;else if (expression) statement if true;else statement if false;
Rule: else matches nearest unmatched if that precedes it
Consider this:
if (num <= 10) if (num >= 3) cout << num << “ is between 3 and 10” << endl;else cout << num << “ is less than 3” << endl;
if (num <= 10) /* braces allow else to go with first if */{ if (num >= 3) cout << num << “ is between 3 and 10” << endl;} else cout << num << “ is less than 3” << endl;
Multiple-Way Selection
Switch statement alternate to nested-if statement called case statement in pseudocode permits up to 10 branches use when selection based on single variable or
simple expression good for menu choices
Switch exampleswitch (num % 10){ case 0: cout << “One’s digit is zero” << endl; break; case 1: cout << “One’s digit is one” << endl; break; case 2: cout << “One’s digit is two” << endl; break; default: cout << “One’s digit is ” << num % 10 << endl;}
Exampleswitch (prize) {
case ‘d’: cout << “You win the diamond ring!” << endl;
break; case ‘c’:
cout << “You win the new car!” << endl; break;
case ‘s’: cout << “You win the $25,000 savings bond!” << endl; break;
case ‘t’: cout << “You win the trip to Belize!” << endl; break;
default: cout << “This is not a winning ticket. Sorry.” << endl;
}
Switch Example for Calling Functions
switch (choice){case 1:
show_assignment();break;
case 2:calc_grade();break;
case 3:give_hints();break;
default:cout << “Not a valid choice.” << endl;cout << “Choose again.” << endl;
}
break The break statement causes an immediate exit
from the switch Without the break, execution falls through from
each case to the next This enables us to specify multiple values that
should cause the same code to be executed without having to repeat the code
But we must be careful to include the break where it belongs
A break is recommended, though not required, at the end of the last case
Switch exampleswitch (CountFrom) { case 5: cout << “5” << endl; case 4: cout << “4” << endl; case 3: cout << “3” << endl; case 2: cout << “2” << endl; case 1: cout << “1” << endl; cout << “Ignition” << endl; cout << “Blast off!” << endl;}
Selection in PseudocodeIf gender = male then
If marital_status = single then
If age > 18 and age < 26 then
print “all criteria met”
Else
print “wrong age”
Endif
Else
print “married male”
Endif
Else
print “wrong gender”
Endif
CASE OF order_item donuts: add 1 to d_count pretzels: add 1 to pr_count pizza: add 1 to pi_count other: print “invalid order” add 1 to error_countENDCASE
Practice Problem
A program is required to read a customer’s id number, a purchase amount and a tax code. The tax has been validated and will be one of the following:
0 tax exempt (0%)1 state sales tax only (3%)2 city and state sales tax (5%)3 special sales tax (7%)
The program must then compute the sales tax and the total amount due and print the customer’s id, purchase amount, sales tax and total amount due.
lec. notes p.111
Practice Problem Write C++ code to ask for a student’s exam
score out of 100. Your program is then to match the exam score to a letter grade and print the grade to the screen. The letter grade is to be calculated as follows:
90 and above A80-89 B70-79 C60-69 Dbelow 60 F
lec. notes p.110
Loop Design
3 kinds of loops pretesting
while loop: while (! infile.eof()) post-testing
do-while loop: counting loop
for loop
Counting Loops in C
for (initialization; condition; modification) {…statement block
}
sum = 0;for (i = 1; i < 11; i++) {
sum += i;}
initialization – assignment statement to set loop control variable
condition – determines when loop will exit
modification – defines how loop control variable will change
for vs. while loop
i = 0;
while (i < 6){ print (“%d”, i); i = i + 1; }
for (i = 0; i < 6; i = i + 1) { printf (“%d”, i); }
These are the same:
initialization
condition
increment
Increment and Decrement Operator As a statement
count++;
In an expression
number = 5;
ans = 2 * (number++);
cout << ans << “ “ << number;
ans = 2 * (++number);
cout << ans << “ “ << number;
Counting Loop Pseudocode
Find Sum Initialize sum to 0 Ask how many numbers Get this_many REPEAT this_many times Read next_num Add next_num to sum END loop Print sumEND
start algorithm
end algorithm
loop
Ways to terminate an input loop
1. Run out of data in file (eof)
2. Ask user if want to continue
3. End with sentinel value
4. Know the number of times loop is to be executed and use for loop or while loop
Problem 1
Write a function to sum the numbers 1 to 10 and display the resulting sum.
lec. notes p.113
Problem 2 - Post-testing Practice
•Write a code segment to prompt for and read the cost of an item until the user types a valid (nonnegative) value. Use a do-while loop.
lec. notes p.112
Problem 3
Write a program that sums a sequence of integers. Assume that the first integer read specifies the number of values remaining to be entered. Your program should read only one value at a time. Use a for loop.
lec. notes p.113
Practice Problem 4
Write nested for loops to print the pattern on the right. Each output statement should print a single asterisk.
*******************************************************
lec. notes p.114
Practice Problem 5
Write a for loop that computes the number of integer values that can be divided evenly by 11 or by 13 in the range of start through end, where start and end are integer variables.
lec. notes p.114