1 copyright (c) 2008 by dennis a. fairclough all rights reserved
TRANSCRIPT
More Control Statementsbased on the original work of Dr. Roger deBryVersion 1.0
1Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Topics
LoopsBreak and continue statementsSoftware development process
Algorithms
2Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
ObjectivesAt the end of this topic, students should be able to:
Correctly use a while statement in a C++ programCorrectly use break and continue statements in a C++ programCorrectly use a do statement in a C++ programCorrectly use a for statement in a C++ programDescribe the stages of software developmentCreate simple algorithms to solve computing problems andcreate UML activity diagrams to describe their algorithms
3Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
The while StatementThe while statement allows the program to execute
the same statement multiple times.
while ( count <= MAX ){ cout << count << ‘ ‘; count ++;}
iscount <= MAX
?
cout << count << ‘ ‘;
count++;
true
this is called the limit
Inside the loop, you must alwaysdo something to the variable beingtested, so that the program will eventually exit the loop
false
4Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
// Using a While Statement with a limit
// main class declarationint main ( ) { const int MAX = 5; int count = 1; while ( count <= MAX ) { cout << count; count++; } }
while the limit has not been reached …
change the number being compared to the limit
5Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
// Using a While Statement with a sentinel
int main ( ) { int value = 1; while ( value != 0 ) { cout << "Enter in a digit between 0 and 9, use 0 to quit:"; cin >> value; cout << "You typed " << value; } cout << "Goodbye!"; }
the sentinel in this case is 0
get another value to compare with the sentinel
6Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Using while to validate input. . .const int MAX = 5;cout << “Enter an integer between 0 and 5;
cin >> input;while ( input < 0 || input > MAX ){ cout << “Invalid input. Try again”; cin >> input;}. . .
7Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
// Nested While
int main ( ) { const int COUNT = 3; const int TIMES = 2; int valueOne, valueTwo; valueOne = 0; while ( valueOne <= COUNT ) { cout << "In outer loop, valueOne = " << valueOne; valueTwo = 0; while ( valueTwo <= TIMES ) { cout << " In inner loop, valueTwo = " << valueTwo; valueTwo++; } valueOne++; } cout << "Goodbye!"; }
8Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
break and continue
break – breaks immediately out of a loop/switch.
continue – skip the rest of the loop and go back and go through the loop another time.
9Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
The do-while Statement
do{ count++; cout << count;} while ( count < LIMIT);
count = count +1;
cout << count;
iscount < LIMIT
?
true
false
in a do statement, the loop willalways be executed at least once!
10Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Validating Input
A common programming problem is to do something,and then ask the user if they want to do it again.
If the user answers “yes” you do it again. If the user answers “no” you stop.
If the user answers neither, tell him to try the answer again.
11Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Write the code …..
12Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
First – our up front boilerplate
#include <iostream>using namespace std;
int main ( ){
13Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Second – declare the variables we will use
int number; // a user entered valuechar yesNo; // store use response to do it againbool okay = true, notDone = false; // some flags
14Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Prompt userFor avalue
Get inputFrom the
user
Display theresult
number
15Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
// prompt, get user input, and display itcout << <\nEnter an integer value: “;cin >> number;cout << “\nYou typed the number “ << number;
16Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Prompt userFor avalue
Get inputFrom the
user
Display theresult
Prompt“Play Again?”
Get inputFrom theuser
InputValid
?
Display anerror
message
no
yesNo
17Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
// prompt to play again – make sure response is validcout << <\nDo you want to play again(y or n)?: “;cin >> yesNo;if(cin.rdbuf()->in_avail()!=0) cin.ignore(80, ‘\n’); // get rid of extra characters
// see if response is valid – print a message if its notokay = (yesNo == ‘y’ || yesNo == ‘n’);if (!okay) cout << “\nSorry, but that is not a valid response.”;
18Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
// prompt to play again – make sure response is validcout << <\nDo you want to play again(y or n)?: “;cin >> yesNo;if(cin.rdbuf()->in_avail()!=0) cin.ignore(80, ‘\n’); // get rid of extra characters
// see if response is valid – print a message if its notokay = (yesNo == ‘y’ || yesNo == ‘n’);if (!okay) cout << “\nSorry, but that is not a valid response.”;
Then here is the first loop – stay in loop until there isa valid response
do{
} while (!okay);
19Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Prompt userFor avalue
Get inputFrom the
user
Display theresult
Prompt“Play Again?”
Get inputFrom the
user
InputValid
?
Display anerror
message
no Playagain
?
yes noend
20Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
#include <iostream>using namespace std;
int main ( ){ int number; char yesNo; bool okay = true, notDone = true;
do // main loop { cout << "\nEnter an integer value: "; cin >> number; cout << "\nYou types the number " << number; do { cout << "\nDo you want to play again (y or n)? "; cin >> yesNo; if(cin.rdbuf()->in_avail()!=0) cin.ignore ( 80, '\n'); // get rid of extra characters okay = ( yesNo == 'y' || yesNo == 'n'); if ( !okay ) cout << "\nSorry, that is not a valid response.” } while (!okay);
if (yesNo == 'n') notDone = false; } while (notDone);}
21Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Apply this code to the guessing gamein the following slide
Practice
22Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
int main ( ) { // We will generate numbers between 0 and 10 const int MAX = 10; int answer, guess; randomize ( ); answer = rand( ) % 11; cout << "I am thinking of a number between 0 and "; cout << MAX << " What is it? "; cin >> guess; if(cin.rdbuf()->in_avail()!=0) cin.ignore(80,’\n’); if ( guess == answer ) cout << "Congratulations. You guessed it.\n"; else { cout << "That is not correct, sorry. "; cout << "The number was " << answer << ‘\n’; } cout << "Thanks for playing.\n"; }
23Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
The for StatementThe for statement is best used when you knowexactly how many times you want to executethe loop.
for ( ){ cout << count;}
initialization evaluation increment
int count = 0;count < LIMIT;count++
Initialize
evaluatecondition
body of loop
increment
24Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
The Comma OperatorThe comma operator is used to evaluate a list of expressions, but onlyreturn the value in the last expression.
goodNum = (first = 2, second = first + 1);
this expression is evaluated firstthen this expression is evaluatedand the result is assigned to goodNum.
25Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
establish the requirements
create the design
implement the code
test the implementation
Development Stages
26Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Algorithm Development
The steps that we come up with to solvea problem are called an algorithm.
An algorithm is like a recipe in a cookbook.Once you come up with an algorithm tosolve a particular problem, you can apply itto other similar problems.
27Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
ProblemYou just purchased a new computer that cost $1000.00. Youdid not have to make a down payment, and your payments are$50.00 a month. The interest rate on your purchase is 18% peryear. How many payments will you have to make to pay off theloan and what is the total interest that you will pay over the lifeof the loan.
Each month when you make a payment, your payment first paysthe interest for that month. The monthly interest rate is 1.5%. Once the interest is paid, the balance of you payment goes towards the balance of the loan.
28Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Step One
Write down everything you know about the problem.
Loan amount = 1000.00
Monthly Payment = 50.00
Interest Rate = 18%
29Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Step Two
Write down what you are looking for
Months to Pay
Total Interest
30Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Interest CalculationEach month when you make a payment, your payment first paysthe interest for that month. The monthly interest rate is 1.5%, sothe first month the interest will be 1.5% x $1000.00, or $15.00. Once the interest is paid, the balance of you payment goes towards the balance of the loan. The first month you will have $35.00 leftafter paying the interest, so subtracting this from the loan balancewill make the new balance $965.00.
The next month, repeat the process, starting with the new balance, $965.00.
31Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Pseudo codePseudo code is an English-like description of the programmingsteps taken to solve a problem.
Write the pseudo code required to calculate the new balance each month
interest = balanceDue x monthlyRate
paymentBalance = payment – interest
balanceDue = balanceDue - paymentBalance
32Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Activity DiagramWe can create what is called an Activity Diagram to show these steps pictorially.
interest = balanceDue x monthlyRate
paymentBalance =payment - interest
balanceDue = balanceDue –
paymentBalance
33Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Building the LoopWe know that we will do this same calculation each month,for some number of months. This suggests that we put thecode we just developed into a loop of some kind. Thepseudo code to describe this might be something like
while the loan is unpaid, do the following:
interest = balanceDue x monthlyRate
paymentBalance = payment – interest
balanceDue = balanceDue - paymentBalance
34Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Adding the Loop to the Diagram
interest = balanceDue x monthlyRate
paymentBalance =payment - interest
balanceDue = balanceDue –
paymentBalance
is the loanpaid off?
yesno
35Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
InitializationTo complete the pseudo code and the diagram, we just need totake care of initializing some things:
interest = balanceDue x monthlyRate
paymentBalance =payment - interest
balanceDue = balanceDue –
paymentBalance
is the loanpaid off?
yesno
monthlyRate = .015balanceDue = 1000.
payment = 50.
36Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Convert to Codedouble balanceDue = 1000.00;double monthlyRate = .015;double payment = 50.00;
double interest = balanceDue * monthlyRate;double paymentBalance = payment – interest;balanceDue = balanceDue – paymentBalance;
What kind of loop?
If there is a balance on the loan, we must go through theloop. If not, we can quit.
37Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
double balanceDue = 1000.00;double monthlyRate = .015;double payment = 50.00;
double interest = balanceDue * monthlyRate;double paymentBalance = payment – interest;balanceDue = balanceDue – paymentBalance;
do{
} while (balanceDue > 0);
38Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Are We Done?
Well, what did the problem ask for?
* The number of months it takes to pay off the loan
* the total interest paid during the life of the loan
Nope …. we haven’t calculated these yet.
How would you fix the program to add these calculations?
39Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
double balanceDue = 1000.00;double monthlyRate = .015;double payment = 50.00double totalInterest = 0.0;int monthsToPay = 0;
double interest = balanceDue * monthlyRate;totalInterest += interest;monthsToPay++;double paymentBalance = payment – interest;balanceDue = balanceDue – paymentBalance;
do{
} while (balanceDue > 0);
40Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Are We Done?
Well …. almost.
We probably ought to print out the results.
41Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
double balanceDue = 1000.00;double monthlyRate = .015;double payment = 50.00double totalInterest = 0.0;int monthsToPay = 0;
double interest = balanceDue * monthlyRate;totalInterest += interest;monthsToPay++;double paymentBalance = payment – interest;balanceDue = balanceDue – paymentBalance;
do{
} while (balanceDue > 0);
cout << Months to pay off loan = “ << monthsToPay << “\n”;cout << “Total interest = “;cout.setf (ios::fixed);cout.setf (ios::showpoint);cout.precision (2);cout << totalInterest << “\n”;
42Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Wrap it up and put a bow on it!
43Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
double balanceDue = 1000.00;double monthlyRate = .015;double payment = 50.00double totalInterest = 0.0;int monthsToPay = 0;
double interest = balanceDue * monthlyRate;totalInterest += interest;monthsToPay++;double paymentBalance = payment – interest;balanceDue = balanceDue – paymentBalance;
do{
} while (balanceDue > 0);cout << Months to pay off loan = “ << monthsToPay << “\n”;cout << “Total interest = “;cout.setf (ios::fixed);cout.setf (ios::showpoint);cout.precision (2);cout << totalInterest << “\n”;
#include <iostream>using std::cin;using std::cout;using std::ios;
int main( ){
{
44Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
PracticeWrite a program that displays the multiplicationtables between 2 and 12. Display the output incolumns, so that it all appears on one screen. Yourtable should be nicely lined up like the following:
2 3 4 5 6 7 8 9 10 11 122 4 6 8 10 12 14 16 18 20 22 243 6 9 12 15 18 21 24 27 30 33 364 8 12 16 20 24 28 32 36 40 44 48
etc . . .
45Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.