Chapter 5 CONTROL STRUCTURES II (Repetition)

Download Report

Transcript Chapter 5 CONTROL STRUCTURES II (Repetition)

CHAPTER 5
CONTROL STRUCTURES II
(Repetition)
In this chapter, you will:
 Learn about repetition (looping) control structures
 Explore how to construct and use count-controlled,
sentinel-controlled, flag-controlled, and EOF-controlled
repetition structures
 Examine break and continue statements
 Discover how to form and use nested control
structures
WHY IS REPETITION NEEDED?
• Suppose we want to add five numbers (say to find their average).
• From what you have learned so far, you could proceed as follows.
cin>>num1>>num2>>num3>>num4>>num5;
sum = num1+num2+num3+num4+num5;
average = sum/5;
• Suppose we wanted to add and average 100, or 1000, or more
numbers.
• We would have to declare that many variables, and list them again in
cin statement, and perhaps, again in the output statement.
• Suppose the numbers we want to add are the following:
5 3 7 9 4
• Consider the following statements.
1. sum = 0;
2. cin>>num;
3. sum = sum + num;
•
•
•
•
Assume sum and num are variables of the type int.
The first statement initializes sum to 0.
Execute statements 2 and 3.
Statement 2 stores 5 in num and statement 3 updates the value of sum
by adding num to it.
• After statement 3 the value of sum is 5.
• Let us repeat statements 2 and 3.
• After statement 2
num = 3
• After statement 3
sum = sum + num = 5 + 3 = 8.
• At this point sum contains the sum of first two numbers.
• Repeat statements 2 and 3 (that is, third time).
• After statement 2
num = 7
• After statement 3
sum = sum + num = 8 + 7 = 15
• Now sum contains the sum of first three numbers.
• If we repeat statements 2 and 3 two more times, sum will contain the
sum of all five numbers.
 To add 10 numbers, you can repeat statements 2 and 3 10 times.
 To add 100 numbers we can repeat statements 2 and 3 100 times.
 You would not have to declare any addition variables as in the
first code.
 There are three repetition or looping structures in C++ that lets
us repeat statements over and over until certain conditions are
met.
THE while LOOPING (REPETITION) STRUCTURE
The general form of the while statement is
while(expression)
statement
• In C++, while is a reserved word.
• The statement can be either a simple or compound statement.
• The expression acts as a decision maker and is usually a logical
expression.
• The statement is called the body of the loop.
• Note that the parentheses around the expression are part of the
syntax.
• The expression provides an entry condition.
• If the expression initially evaluates to true, the statement
executes.
• The loop condition—the expression—is then reevaluated. If it
again evaluates to true, the statement executes again.
• The statement (body of the loop) continues to execute until the
expression is no longer true.
• A loop that continues to execute endlessly is called an infinite loop.
• To avoid an infinite loop, make sure that the loop’s body contains
statement(s) that assure that the exit condition—the expression
in the while statement—will eventually be false.
Example 5-1
i = 0;
//Line 1
while(i <= 20)
//Line 2
{
cout<<i<<" ";
i = i + 5;
}
Output:
0 5 10 15 20
//Line 3
//Line 4
• At Line 1, the variable i is set to 0.
• The expression in the while statement (at Line 2), i <= 20,
is evaluated. Since the expression i <= 20 evaluates to true, the
body of the while loop executes next.
• The body of the while loop consists of the statements at Lines 3
and 4.
• The statement at Line 3 outputs the value of i, which is 0.
• The statement at Line 4 changes the value of i to 5.
• After executing the statements at Lines 3 and 4, the expression in
the while loop (at Line 2) is evaluated again.
• Since i is 5, the expression i <= 20 evaluates to true and the
body of the while loop executes again.
• This process of evaluating the expression and executing the body
of the while loop continues until the expression, i < 20 (at
Line 2), no longer evaluates to true.
• The variable i (Line 2) in the expression is called the loop control
variable.
Within the loop i becomes 25, but is not printed since
a.
the entry condition is false.
b.
If we omit the statement
i = i + 5;
c.
from the body of the loop, we have an infinite loop, continually
printing rows of zeros.
The loop control variable in the while statement must be
initialized before entry. If the statement
i = 0;
(at Line 1) is omitted, the loop may not execute at all. (Recall that
variables in C++ are not automatically initialized.)
d.
In the above program segment if the two statements in the
body of the loop are interchanged, it may very well cause a
drastic alteration in the result.
i = 0;
while(i <= 20)
{
i = i + 5;
cout<<i<<" ";
}
Output:
5 10 15 20 25
Example 5-2
i = 20;
while(i < 20)
{
cout<<i<<" ";
i = i + 5;
}
//Line 1
//Line 2
//Line 3
//Line 4
Here no values will be output.
Case 1: Counter-Controlled while Loops
counter = 0;
while(counter < N)
{
.
.
.
counter++;
.
.
.
}
Example 5-3
Suppose the input is
12 8 9 2 3 90 38 56 8 23 89 7 2 8 3 8
The first number, 12, specifies the number of values there are to be.
// Program: AVG1
#include <iostream>
using namespace std;
int
{
main()
int limit;
// store the number of items
// in the list
int number; // variable to store the number
int sum;
// variable to store the sum
int counter; // loop control variable
cout<<"Line 1: Enter data for processing"
<<endl;
//Line 1
cin>>limit;
//Line 2
sum = 0;
counter = 0;
//Line 3
//Line 4
while(counter < limit)
{
cin>>number;
sum = sum + number;
counter++;
}
cout<<"Line 9: The sum of "<<limit
<<" numbers = "<<sum<<endl;
if(counter != 0)
cout<<"Line 11: The average = "
<<sum / counter<<endl;
else
cout<<"Line 13: No input."<<endl;
return 0;
}
//Line 5
//Line 6
//Line 7
//Line 8
//Line 9
//Line 10
//Line 11
//Line 12
//Line 13
Sample Run: The user input is in red.
Line
12 8
Line
Line
1: Enter data for processing
9 2 3 90 38 56 8 23 89 7 2 8 3 8
9: The sum of 12 numbers = 335
11: The average = 27
Case 2: Sentinel Controlled while Loop
cin>>variable;
while(variable != sentinel)
{
.
.
.
cin>> variable;
.
.
.
}
Example 5-4
Suppose you want to read some positive integers and
average them, but you do not have a preset number of data
items in mind. Suppose the number –999 marks the end
of data.
//Program: AVG2
#include <iostream>
using namespace std;
const int SENTINEL = -999;
int main()
{
int number;
int sum = 0;
int count = 0;
//
//
//
//
variable to store the number
variable to store the sum
variable to store the total
number read
cout<<"Line 1: Enter numbers ending with "
<<SENTINEL<<endl;
//Line 1
cin>>number;
//Line 2
while(number != SENTINEL)
{
sum = sum + number;
count++;
cin>>number;
}
//Line 3
//Line 4
//Line 5
//Line 6
cout<<"Line 7: The sum of "<<count
<<" numbers is "<<sum<<endl;
if(count != 0)
cout<<"Line 9: The average is "
<<sum / count<<endl;
else
cout<<"Line 11: No input."<<endl;
return 0;
}
Sample Run: The user input is in red.
Line 1: Enter numbers ending with -999
34 23 9 45 78 0 77 8 3 5 -999
Line 7: The sum of 10 numbers is 282
Line 9: The average is 28
//Line 7
//Line 8
//Line 9
//Line 10
//Line 11
Example 5-5: Telephone Digits
//*****************************************************
// Program: Telephone Digits
// This is an example of a sentinel-controlled loop. This
// program converts uppercase letters to their
// corresponding telephone digits.
//******************************************************
#include <iostream>
using namespace std;
int main()
{
char letter;
//Line 1
cout<<"This program converts uppercase "
<<"letters to their corresponding "
<<"telephone digits."<<endl;
//Line 2
cout<<"To stop the program enter Q or Z."<<endl;
//Line 3
cout<<"Enter a letter--> ";
cin>>letter;
//Line 4
//Line 5
cout<<endl;
//Line 6
while(letter != 'Q' && letter != 'Z' )
{
cout<<"The letter you entered is --->
<<letter<<endl;
cout<<"The corresponding telephone "
<<"digit is --> ";
if(letter >= 'A' && letter <= 'Z')
//Line 7
"
//Line 8
//Line 9
//Line 10
switch(letter)
{
case 'A': case 'B': case 'C': cout<<"2\n";
break;
case 'D': case 'E': case 'F': cout<<"3\n";
break;
case 'G': case 'H': case 'I': cout<<"4\n";
break;
case 'J': case 'K': case 'L': cout<<"5\n";
break;
case 'M': case 'N': case 'O': cout<<"6\n";
break;
case 'P': case 'R': case 'S': cout<<"7\n";
break;
case 'T': case 'U': case 'V': cout<<"8\n";
break;
case 'W': case 'X': case 'Y': cout<<"9\n";
}
//Line 11
//Line
//Line
//Line
//Line
//Line
//Line
//Line
//Line
//Line
//Line
//Line
//Line
//Line
//Line
//Line
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
else
//Line 27
cout<<"You entered a bad letter."<<endl;
//Line 28
cout<<"\nEnter another uppercase letter to be"
<<" \nconverted to the corresponding "
<<"telephone digits."<<endl<<endl;//Line 29
cout<<"To stop the program enter Q or Z."
<<endl<<endl;
//Line 30
cout<<"Enter a letter--> ";
//Line 31
cin>>letter;
//Line 32
cout<<endl;
//Line 33
}//end while
return 0;
}
Sample Run: The user input is in red.
This program converts uppercase letters to their
corresponding telephone digits.
To stop the program enter Q or Z.
Enter a letter--> A
The letter you entered is ---> A
The corresponding telephone digit is --> 2
Enter another uppercase letter to be
converted to the corresponding telephone digits.
To stop the program enter Q or Z.
Enter a letter--> D
The letter you entered is ---> D
The corresponding telephone digit is --> 3
Enter another uppercase letter to be
converted to the corresponding telephone digits.
To stop the program enter Q or Z.
Enter a letter--> Q
Case 3: Flag-Controlled while Loops
• A flag controlled while loop uses a Boolean variable to control the
loop. Suppose found is a Boolean variable. The flag controlled
while loop takes the form:
found = false;
while(!found)
{
.
.
.
if(expression)
found = true;
.
.
.
}
Case 4: EOF Controlled while Loop
An input stream variable, such as cin, returns a value, after reading
data, as follows:
1. If the program has reached the end of input data, the input stream
variable returns the logical value false.
2. If the program reads a faulty data (such as char into int), the
input stream enters into the fail state. Once a stream has entered the
fail state, any further I/O operations using that stream are
considered to be null operations, that is, they have no effect at all.
Unfortunately for us the computer does not halt the program or give
any error messages. The computer just continues executing the
program, silently ignoring each additional attempt to use that
stream. In this case cin returns the value false.
3. In cases other than (1) and (2), it returns the logical value true.
 The value returned by cin can be used to determine if the program
has reached the end of input data.
 Since cin returns a logical value true or false, in a while loop
it can be considered a logical expression.
 An example of an EOF controlled while loop is:
cin>>variable;
while(cin)
{
.
.
.
cin>>variable;
.
.
.
}
The eof Function
• In addition to checking the value of an input stream variable, such as
cin, to determine whether the end of file has been reached, the
function eof with an input stream variable can also be used to
determine the end of file status.
• Like the I/O functions, such as get, ignore, and peek, the
function eof is also a member of data type istream.
The syntax to use the function eof is:
istreamVar.eof()
where istreamVar is an input stream variable, such as cin.
Suppose we have the following declaration:
ifstream infile;
Consider the expression:
infile.eof()
• This is a logical (Boolean) expression.
• The value of this expression is true if the program has read past the
end of the input file, infile, otherwise the value of this expression
is false.
• This method of determining the end of file status works best if the
input is text.
• The earlier method of determining the end-of-file status works better
if the input consists of numeric data.
Suppose we have the declaration:
ifstream
char ch;
infile;
infile.open("inputDat.dat");
• The following while loop continues to execute as long as the program
has not reached the end of file.
infile.get(ch);
while(!infile.eof())
{
cout<<ch;
infile.get(ch);
}
• As long as the program has not reached the end of the input file, the
expression
infile.eof()
is false and so the expression
!infile.eof()
in the while statement is true.
• When the program reads past the end of the input file, the expression
infile.eof()
becomes true and so the expression
!infile.eof()
in the while statement will become false and the loop
terminates.
PROGRAMMING EXAMPLE: CHECKING
ACCOUNT BALANCE
A local bank in your town is looking for someone to write a program
that calculates a customer’s checking account balance at the end of
each month. The data is stored in a file in the following form:
467343 23750.40
W 250.00
D 1200
W 75.00
I 120.74
.
.
.
• The first line of data shows the account number followed by the
account balance at the beginning of the month.
• Thereafter each line has two entries: the transaction code and the
transaction amount.
• The transaction code W or w means withdrawal, D or d means deposit,
and I or i means interest paid by the bank.
• The program updates the balance after each transaction.
• During the month, if at any time the balance goes below $1000.00, a
$25.00 service fee is charged.
• The program prints the following information: account number,
balance at the beginning of the month, balance at the end of the
month, interest paid by the bank, total amount of deposit, number of
deposits, total amount of withdrawal, number of withdrawals, and
service charge if any.
Input:
A file consisting of data in the above format.
Output:
The output is of the following form:
Account Number: 467343
Beginning Balance: $23750.40
Ending Balance: $24611.49
Interest Paid: $366.24
Amount Deposited: $2230.50
Number of Deposits: 3
Amount Withdrawn: $1735.65
Number of Withdrawals: 6
Problem Analysis and Algorithm Design
• The first entry in the input file is the account number and the
beginning balance.
• The program first reads the account number and the beginning
balance.
• Thereafter, each entry in the file is of the following form:
transactionCode transactionAmount
• To determine the account balance at the end of the month, you need
to process each entry that contains the transaction code and
transaction amount.
• Begin with the starting balance and then update the account balance
after processing each entry.
• If the transaction code is D, d, I or i, the transaction amount is
added to the account balance.
• If the transaction code is W or w, the transaction amount is subtracted
from the balance.
• Since the program also outputs the number of withdrawals and
deposits, you need to keep separate counts of withdrawals and
deposits.
• This discussion translates into the following algorithm:
1. Declare the variables.
2. Initialize the variables.
3. Get the account number and beginning balance.
4. Get the transaction code and transaction amount.
5. Analyze the transaction code and update the appropriate variables.
6. Repeat Steps 4 and 5 until there is no more data.
7. Print the result.
Variables
acctNumber
//variable to store account number
beginningBalance
//variable to store
//beginning balance
accountBalance
//variable to store
//account balance at the
//end of the month
amountDeposited //variable to store total
//amount deposited
numberOfDeposits
//variable to store the
//number of deposits
amountWithdrawn
//variable to store total
//amount withdrawn
numberOfWithdrawals //variable to store number
//of withdrawals
interestPaid
//variable to store interest
//amount paid
int
double
double
double
int
double
int
double
char
double
acctNumber;
beginningBalance;
accountBalance;
amountDeposited;
numberOfDeposits;
amountWithdrawn;
numberOfWithdrawals;
interestPaid;
transactionCode;
transactionAmount;
bool
isServiceCharged;
ifstream infile;
ofstream outfile;
//input file stream variable
//output file stream variable
Named Constants
const double minimumBalance = 1000.00;
const double serviceCharge = 25.00;
1. Declare the variables. Declare variables as discussed previously.
2. Initialize the variables.
• Initialize
the
variables
amountDeposited,
numberOfDeposits
amountWithdrawn,
numberOfWithdrawals, and interestPaid must be
initialized to 0. The variable isServicedCharged is
initialized to false. You can initialize these variables when you
declare them.
• After reading the beginning balance in the variable
beginningBalance from the file, initialize the variable
accountBalance to the value of the variable
beginningBalance.
• Since the data will be read from a file, you need to open the input
file. The following code opens the files:
infile.open("a:money.txt"); //open input file
if(!infile)
{
cout<<"Cannot open input file"<<endl;
cout<<"Program terminates!!!"<<endl;
return 1;
}
outfile.open("a:money.out"); //open input file
3. Get the account number and starting balance.
infile>>acctNumber>>beginningBalance;
4. Get the transaction code and transaction amount.
infile>>transactionCode>>transactionAmount;
5. Analyze the transaction code and update the appropriate
variables
switch(transactionCode)
{
case 'D':
case 'd': accountBalance = accountBalance
+ transactionAmount;
amountDeposited = amountDeposited
+ transactionAmount;
numberOfDeposits++;
break;
case 'I':
case 'i': accountBalance = accountBalance
+ transactionAmount;
interestPaid = interestPaid
+ transactionAmount;
break;
case 'W':
case 'w': accountBalance = accountBalance
- transactionAmount;
amountWithdrawn = amountWithdrawn
+ transactionAmount;
numberOfWithdrawals++;
if((accountBalance < minimumBalance)
&& (!isServiceCharged))
{
accountBalance = accountBalance
- serviceCharge;
isServiceCharged = true;
}
break;
default: cout<<"Invalid transaction code"<<endl;
} //end switch
6. Repeat Steps 4 and 5 until there is no more data. Since the
number of entries in the input file is not known, the program needs
an EOF-controlled while loop.
7. Print the result: This is accomplished by using output statements.
Main Algorithm
1. Declare and initialize the variables.
2. Open the input file.
3. If the input file does not exist, exit the program.
4. Open the output file.
5. To output floating-point numbers in a fixed decimal format with the
decimal point and trailing zero, set the manipulators fixed and
showpoint. To output floating-point numbers to two decimal
places, set the precision to two decimal places.
6. Read accountNumber and beginningBalance.
7. Set accountBalance to beginningBalance.
8. Read transactionCode and transactionAmount.
9. While (not end of input file)
a. If transactionCode is 'D'
i. Add transactionAmount to accountBalance
ii. Increment numberOfDeposits
b. If transactionCode is 'I'
i. Add transactionAmount to accountBalance
ii. Add transactionAmount to interestPaid
c. If transactionCode is 'W'
i. Subtract transactionAmount from accountBalance
ii. Increment numberOfWithDrawals
iii. If (accountBalance < minimumBalance
&& !isServicedCharged)
1. Subtract serviceCharge from accountBalance
2. Set isServiceCharged to true
d. If transactionCode is other than 'D', 'd', 'I', 'i',
'W', or 'w', output an error message.
10. Output the results.
//*******************************************************
// Program -- Checking Account Balance.
// This program calculates a customer’s checking account
// balance at the end of the month.
//*******************************************************
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const double minimumBalance = 1000.00;
const double serviceCharge = 25.00;
int main()
{
//Declare and initialize variables
int acctNumber;
double beginningBalance;
double accountBalance;
double amountDeposited = 0.0;
int numberOfDeposits = 0;
//Step 1
double amountWithdrawn = 0.0;
int numberOfWithdrawals = 0;
double interestPaid = 0.0;
char transactionCode;
double transactionAmount;
bool isServiceCharged = false;
ifstream infile;
ofstream outfile;
infile.open("a:Ch5_money.txt");
//Step 2
if(!infile)
//Step 3
{
cout<<"Cannot open input file"<<endl;
cout<<"Program terminates!!!"<<endl;
return 1;
}
outfile.open("a:Ch5_money.out");
//Step 4
outfile<<fixed<<showpoint;
outfile<<setprecision(2);
//Step 5
//Step 5
cout<<"Processing data"<<endl;
infile>>acctNumber>>beginningBalance;
//Step 6
accountBalance = beginningBalance;
//Step 7
infile>>transactionCode>>transactionAmount;
//Step 8
while(infile)
//Step 9
{
switch(transactionCode)
{
case 'D':
//Step 9.a
case 'd': accountBalance = accountBalance
+ transactionAmount;
amountDeposited = amountDeposited
+ transactionAmount;
numberOfDeposits++;
break;
case 'I':
//Step 9.b
case 'i': accountBalance = accountBalance
+ transactionAmount;
interestPaid = interestPaid
+ transactionAmount;
break;
case 'W':
//Step 9.c
case 'w': accountBalance = accountBalance
- transactionAmount;
amountWithdrawn = amountWithdrawn
+ transactionAmount;
numberOfWithdrawals++;
if((accountBalance < minimumBalance)
&& (!isServiceCharged))
{
accountBalance = accountBalance
- serviceCharge;
isServiceCharged = true;
}
break;
default: cout<<"Invalid transaction code"
<<endl;
} //end switch
infile>> transactionCode>>transactionAmount;
}//end while
//Output Results
//Step 10
outfile<<"Account Number: "<<acctNumber<<endl;
outfile<<"Beginning Balance: $"
<<beginningBalance<<endl;
outfile<<"Ending Balance: $"<<accountBalance
<<endl<<endl;
outfile<<"Interest Paid: $"<<interestPaid
<<endl<<endl;
outfile<<"Amount Deposited: $"
<<amountDeposited<<endl;
outfile<<"Number of Deposits: "<<numberOfDeposits
<<endl<<endl;
outfile<<"Amount Withdrawn: $"
<<amountWithdrawn<<endl;
outfile<<"Number of Withdrawals: "
<<numberOfWithdrawals
<<endl<<endl;
if(isServiceCharged)
outfile<<"Service Charge: $"
<<serviceCharge<<endl;
return 0;
}
Sample Run: (Contents of the output file A:Ch5_money.out)
Account Number: 467343
Beginning Balance: $23750.40
Ending Balance: $24611.49
Interest Paid: $366.24
Amount Deposited: $2230.50
Number of Deposits: 3
Amount Withdrawn: $1735.65
Number of Withdrawals: 6
Input File: (A:CH5_money.txt)
467343 23750.40
W 250.00
D 1200.00
W 75.00
I 120.74
W 375.00
D 580.00
I 245.50
W 400.00
W 600.00
D 450.50
W 35.65
PROGRAMMING EXAMPLE: FIBONACCI NUMBER
• Consider the following sequence of numbers,
1, 1, 2, 3, 5, 8, 11, 19, 30, ....
• Given the first two numbers of the sequence say a1 and a2, the nth
number an , n >= 3, of this sequence is given by
an = an-1 + an-2.
Thus
a3 =
=
a4 =
=
=
a2 +a1
1 + 1 = 2;
a3 + a2
1 + 2
3,
• Such a sequence is called a Fibonacci sequence. In the above
sequence a2 = 1 and a1 = 1. However, given any first two numbers,
we can determined the nth number, an, n >= 3, of the sequence.
The number determined this way is called the nth Fibonacci
number.
Suppose a2 = 6 and a1 = 3. Then
a3 = a2 +a1 = 6 + 3 = 9; a4 = a3
+ a2 = 9 + 6 = 15
Input: The first two Fibonacci numbers and the desired Fibonacci
number.
Output: The nth Fibonacci number.
Problem Analysis and Algorithm Design
• To find, say a10 the 10th Fibonacci number of a sequence, we first
find a9 and a8, which will require us to find a7 and a6 and so on.
• Thus, in order to find a10, first we must find a3, a4, a5,..., a9.
This discussion translates into the following algorithm.
1. Get the first two Fibonacci numbers.
2. Get the desired Fibonacci number. That is, get the position, n, of the
Fibonacci number in the sequence.
3. Calculate the next Fibonacci number of the sequence by adding the
previous two elements of the Fibonacci sequence.
4. Repeat Step 2 until the nth Fibonacci number has been found.
5. Output the nth Fibonacci number.
Variables
int previous1;
int previous2,
int current;
int counter;
int nthFibonacci;
//
//
//
//
//
//
//
//
//
Variable to store the first
Fibonacci number
Variable to store the second
Fibonacci number
Variable to store the
current Fibonacci number
Loop control variable
Variable to store the
desired Fibonacci number
Main Algorithm
1. Prompt the user for the first two numbers, that is, previous1 and
previous2.
2. Read (input) the first two numbers into previous1 and
previous2.
3.
4.
5.
6.
Output the first two Fibonacci numbers. (Echo input.)
Prompt the user for the desired Fibonacci number.
Read the desired Fibonacci number into nthFibonacci.
Since we already know the first two Fibonacci numbers of the
sequence, we start with determining the third Fibonacci number. So
initialize counter to 3, in order to keep track of the calculated
numbers.
7. Calculate the next Fibonacci number.
current = previous2 + previous1;
8. Assign the value of previous2 to previous1.
9. Assign the value of current to previous2.
10. Increment counter.
11. Repeat Steps 7-10 until the desired Fibonacci number has been
calculated:
The following while loop executes Step 7-10 and determines the
nthFibonacci number.
while(counter <= nthFibonacci)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
current++;
}
12. Output the nthFibonacci number, which is current
// Program: nth Fibonacci number
#include <iostream>
using namespace std;
int
{
main()
//Declare variables
int previous1;
int previous2;
int current;
int counter;
int nthFibonacci;
cout<<"Enter the first two Fibonacci "
<<"numbers -> ";
//Step
cin>>previous1>>previous2;
//Step
cout<<"\nThe first two Fibonacci numbers "
<<"are "<<previous1<<" and "<<previous2;
//Step
cout<<"\nEnter the desired Fibonacci "
<<"number to be determined ->";
//Step
cin>>nthFibonacci;
//Step
1
2
3
4
5
counter = 3;
//Steps 7-10
while(counter <= nthFibonacci)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
counter++;
}
//Step 6
//Step
//Step
//Step
//Step
7
8
9
10
cout<<"\n\nThe "<<nthFibonacci
<<"th Fibonacci number is: "<<current
<<endl;
//Step 12
return 0;
}//end main
Sample Run:The user input is in red.
Sample Run 1:
Enter the first two Fibonacci numbers -> 12 16
The first two Fibonacci numbers are 12 and 16
Enter the desired Fibonacci number to be determined
->10
The 10th Fibonacci number is 796.
Sample Run 2:
Enter the first two Fibonacci numbers -> 1 1
The first two Fibonacci numbers are 1 and 1
Enter the desired Fibonacci number to be determined
->15
The 15th Fibonacci number is 610.
THE for LOOPING (REPETITION) STRUCTURE
The general form of the for statement is
for(initial statement; loop condition;
update statement)
statement
• The initial statement, loop condition and update
statement (called for loop control statements) that are enclosed
with in the parentheses controls the body (the statement) of the for
statement.
 The for loop executes as follows:
1. The initial statement executes.
2. The loop condition is evaluated.
a. If the loop condition evaluates to true
i. Execute the for loop statement.
ii. Execute the update statement (the third expression in the
parentheses).
3. Repeat Step 2 until the loop condition evaluates to false.
 The initial statement usually initializes a variable (called the
for loop control variable, or indexed variable).
 In C++, for is a reserved word.
 As the name implies, the initial statement in the for loop is
the first statement to be executed and is executed only once.
Example 5-6
The following for loop prints the first 10 positive integers:
for(i = 1; i <= 10; i++)
cout<<i<<" ";
 The statement of a for loop may be a simple or a compound
statement.
Example 5-7
1. The following for loop outputs the line of text and a star (on
separate lines) five times:
for(i = 1; i <= 5; i++)
{
cout<<"Output a line of stars."<<endl;
cout<<"*"<<endl;
}
2.
for(i = 1; i <= 5; i++)
cout<<"Output a line of stars."<<endl;
cout<<"*"<<endl;
• This loop outputs the line of text five times and the star only once.
• The for loop controls only the first cout statement because the two
cout statements are not made into a compound statement.
• The first cout statement executes five times because the for loop
executes five times.
• After the for loop executes, the second cout statement executes
only once.
3. The following for loop executes five empty statements:
for(i = 1; i <= 5; i++);
cout<<"*"<<endl;
//Line 1
//Line 2
• The semicolon at the end of the for statement (before the cout
statement, Line 1) terminates the for loop.
• The action of this for loop is empty.
Some comments on for loops:
 If the loop condition is initially false, the loop body does not
execute.
 The update expression, when executed, changes the value of the
loop control variable (initialized by the initial expression), which
eventually sets the value of the loop condition to false. The for
loop executes indefinitely if the loop condition is always true.
 C++ allows you to use fractional values for loop control variables of
the double type (or any real data type). Because different
computers can give these loop control variables different results,
you should avoid using such variables.
 A semicolon at the end of the for statement (just before the body of
the loop) is a semantic error. In this case, the action of the for loop
is empty.
 In the for statement, if the loop condition is omitted, it is
assumed to be true.
 In a for statement, you can omit all three statements—initial
statement, loop condition, and update statement. The
following is a legal for loop:
for(;;)
cout<<"Hello"<<endl;
Example 5-8
1.
for(i = 10; i >= 1; i--)
cout<<" "<<i;
The output is
10 9 8 7 6 5 4 3 2 1
2. The following for loop outputs the first 10 positive odd integers.
for(i = 1; i <= 20; i = i + 2)
cout<<" "<<i;
Example 5-9
for(i = 10; i <= 9; i++)
(a)
cout<<i<<" ";
 In this for loop, the initial statement sets i to 10.
 Since initially the loop condition (i <= 9) is false, nothing
happens.
(b)
for(i = 9; i >= 10; i--)
cout<<i<<" ";
 In this for loop, the initial statement sets i to 9.
 Since initially the loop condition (i >= 10) is false, nothing
happens.
for(i = 10; i <= 10; i++)
cout<<i<<" ";
(c)

(d)
In this for loop, the cout statement executes once.
for(i = 1; i <= 10; i++);
cout<<i<<" ";
 This for loop has no effect on the cout statement.
 The semicolon at the end of the for statement terminates the for
loop; the action of the for loop is thus empty.
 The cout statement is all by itself and executes only once.
(e) for(i = 1; ; i++)
cout<<i<<" ";
 In this for loop, since the loop condition is omitted from the
for statement, the loop condition is always true.
 This is an infinite loop.
Example 5-10
 In this example, a for loop reads five numbers and finds their sum
and average.
sum = 0;
for(i = 1; i <= 5; i++)
{
cin>>newNum;
sum = sum + newNum;
}
average = sum / 5;
cout<<"The sum is "<<sum<<endl;
cout<<"The average is "<<average<<endl;
Example 5-11
// Program: sum first n numbers
// This program finds the sum of the first n positive integers.
#include <iostream>
using namespace std;
int main()
{
int counter; // loop control variable
int sum; // variable to store the sum of numbers
int N;
// variable to store the number of
// first positive integers to be added
cout<<"Line 1: Enter the number of positive "
<<"integers to be added:"<<endl;
//Line 1
cin>>N;
//Line 2
sum = 0;
//Line 3
for(counter = 1; counter <= N; counter++)//Line 4
sum = sum + counter;
//Line 5
cout<<"Line 6: The sum of the first "<<N
<<" positive integers is "<<sum<<endl;//Line 6
return 0;
}
Sample Run: In this sample run, the user input is in red.
Line 1: Enter the number of positive integers to be added:
100
Line 6: The sum of the first 100 positive integers is 5050
PROGRAMMING EXAMPLE: CLASSIFY NUMBERS
• This program reads a given set of integers and then prints the number
of odd and even integers. It also outputs the number of zeros.
• The program reads 20 integers, but you can easily modify it to read
any set of numbers.
Input: 20 integers, positive, negative, or zeros.
Output: The number of zeros, even, and odd numbers.
Problem Analysis and Algorithm Design
• After reading a number you need to check whether it is even or odd.
• Suppose the value is stored in number.
• Divide number by 2 and check the remainder.
• If the remainder is zero, number is even. Increment the even count
and then check whether number is zero. If it is, increment the zero
count.
• If the remainder is not zero, increment the odd count.
• The program uses a switch statement to decide whether number is
odd or even.
• Suppose that number is odd. Dividing by 2 gives the remainder 1 if
number is positive and the remainder –1 if negative.
• If number is even, dividing by 2 gives the remainder 0 whether
number is positive or negative.
• You can use the mod operator, %, to find the remainder. For example,
6 % 2 = 0, -4 % 2 = 0,
-7 % 2 = -1, 15 % 2 = 1.
• Repeat the preceding process of analyzing a number for each number
in the list.
• This discussion translates into the following algorithm.
1. For each number in the list
a. Get the number
b. Analyze the number
c. Increment appropriate count.
2. Print results.
Variables:
int
int
int
int
int
counter;
number;
zeros;
evens;
odds;
//loop control variable
//variable to store the
//variable to store the
//variable to store the
//variable to store the
number read
zero count
even count
odd count
• The variables zeros, evens, and odds need to be initialized to
zero and these variables can be initialized when we declare them.
Main Algorithm
1. Initialize variables.
2. Prompt the user to enter 20 numbers.
3. For each number in the list
a. Read the number
b. Output the number (echo input)
c. If the number is even
{
i. Increment the even count.
ii. If number is zero, increment the zero count.
}
otherwise
Increment the odd count
4. Print results.
1. Initialize the variables. You can initialize the variables zeros,
evens, and odds when you declare them.
2. Use an output statement to prompt the user to enter 20 numbers.
3. For Step 3, you can use a for loop to process and analyze the 20
numbers.
for(counter = 1; counter <= 20; counter++)
{
read the number;
output number;
switch(number % 2) //check the remainder
{
case 0: increment even count;
if(number == 0)
increment zero count;
break;
case 1: case –1: increment odd count;
}//end switch
}//end for
4. Print the result. Output the value of the variables zeros, evens,
and odds.
//********************************************************
// Program: Counts zeros, odds, and evens
// This program counts the number of odd and even numbers.
// The program also counts the number of zeros.
//********************************************************
#include <iostream>
#include <iomanip>
using namespace std;
const int N = 20;
int main ()
{
//Declare variables
int counter; //loop control variable
int number;
//variable to store the new number
int zeros = 0;
// Step1
int odds = 0;
// Step1
int evens = 0;
// Step1
cout<<"Please enter "<<N<<" integers, "
<<"positive, negative, or zeros."
<<endl;
//Step 2
cout<<"The numbers you entered are --> "<<endl;
for(counter = 1; counter <= N; counter++)//Step 3
{
cin>>number;
//Step 3a
cout<<setw(5)<< number;
//Step 3b
//Step 3c
switch(number % 2)
{
case 0: evens++;
if(number == 0)
zeros++;
break;
case 1:
case -1: odds++;
} //end switch
} // end for loop
cout<<endl;
//Step 4
cout<<"There are "<<evens<<" evens, "
<<"which also includes "<<zeros
<<" zeros"<<endl;
cout<<"Total number of odds are: "<<odds<<endl;
return 0;
}
Sample Run: In this sample run, the user input is in red.
Please enter 20 integers, positive, negative, or zeros.
The numbers you entered are -->
0 0 -2 -3 -5 6 7 8 0 3 0 -23 -8 0 2 9 0 12 67 54
0
0
-2
-3
-5
6
7
8
0
3
0 -23
-8
0
2
9
0
12
67
54
There are 13 evens, which also includes 6 zeros
Total number of odds are: 7
THE do…while LOOPING (REPETITION)
STRUCTURE
The general form of a do...while statement is:
do
statement
while(expression);
 In C++, do is a reserved word.
 The statement executes first, and then the expression is
evaluated.
 If the expression evaluates to true, the statement executes
again.
 As long as the expression in a do...while statement is
true, the statement executes.
 To avoid an infinite loop, you must, once again, make sure that the
loop body contains a statement that ultimately makes the
expression false and assures that it exits.
 The statement can be a simple or a compound statement. If it is a
compound statement, it must be enclosed between braces.
Example 5-12
do
{
cout<<i<<" ";
i = i + 5;
}
while(i <= 20);
The output is:
0 5 10 15 20
 Because the while and for loop has an entry condition, it may
never activate, whereas, the do...while loop, which has an exit
condition, always goes through at least once.
Example: Consider the following two loops
(a)
(b)
i = 11;
i = 11;
while(i <= 10)
do
{
{
cout<<i<<" ";
cout<<i<<" ";;
i = i + 5;
i = i + 5;
}
}
while(i <= 10);
In (a), the while loop, produces nothing.
In (b) the do...while loop, outputs the number 11.
Example 5-14
//*******************************************************
// Program: Warning Message
// This program reads a value and prints a warning
// message, or rings a bell, when a value falls outside
// a given range.
//*******************************************************
#include <iostream>
using namespace std;
const int low = 60;
const int high = 100;
int main ()
{
int pressure;
do
cin>>pressure;
while((pressure > low) && (pressure < high));
cout<<"Help"<<endl;
return 0;
}
BREAK AND CONTINUE STATEMENTS
 A break and continue statement alters the flow of control.
 The break statement, when executed in a switch structure,
provides an immediate exit from the switch structure.
 You can use the break statement in while, for, and
do...while loops.
 When the break statement executes in a repetition structure, it
immediately exits from these structures.
 The break statement is typically used for two purposes:
1. To exit early from a loop
2. To skip the remainder of the switch structure
 After the break statement executes, the program continues to
execute with the first statement after the structure.
• The use of a break statement in a loop can eliminate the use of
certain (flag) variables.
sum = 0;
cin>>num;
isNegative = false;
while(cin && !isNegative)
{
if(num < 0)
//if number is negative, terminate the loop
{
cout<<"Negative number found in the data"<<endl;
isNegative = true;
}
else
{
sum = sum + num;
cin>>num;
}
}
 The following while loop is written without using the variable
isNegative:
sum = 0;
cin>>num;
while(cin)
{
if(num < 0)
{
//if number is negative, terminate the loop
cout<<"Negative number found in the data"<<endl;
break;
}
sum = sum + num;
cin>>num;
}
• The continue statement is used in while, for, and do-while
structures.
• When the continue statement is executed in a loop, it skips the
remaining statements in the loop and proceeds with the next iteration of
the loop.
• In a while and do-while structure, the expression (that is, the
loop-continue test) is evaluated immediately after the continue
statement.
• In a for structure, the update statement is executed after the
continue statement, and then the loop condition (that is, the
loop-continue test) executes.
sum = 0;
cin>>num;
while(cin)
{
if(num < 0)
{
cout<<"Negative number found in the data"<<endl;
continue;
}
sum = sum + num;
cin>>num;
}
NESTED CONTROL STRUCTURES
#include <iostream>
using namespace std;
int
{
main ()
int
studentId, testScore, count = 0;
cin>>studentId;
while(studentId != -1)
{
count++;
cin>>testScore;
cout<<"Student Id = "<<studentId<<", test score = "
<<testScore<<", and grade = ";
if(testScore >= 90)
cout<<"A."<<endl;
else
if(testScore >= 80)
cout<<"B."<<endl;
else
if(testScore >= 70)
cout<<"C."<<endl;
else
if(testScore >= 60)
cout<<"D."<<endl;
else
cout<<"F."<<endl;
cin>>studentId;
}// end while
cout<<endl<<"Students in class = "<<
return 0;
}
count<<endl;
• Suppose we want to create the following pattern.
*
**
***
****
*****
• In the first line we want to print one star, in the second line two stars
and so on.
• Since five lines are to be printed, we start with the following for
statement.
for(i = 1; i <= 5 ; i++)
• The value of i in the first iteration is 1, in the second iteration it is 2,
and so on.
• We can use the value of i as the limiting condition in another for
loop nested within this loop to control the number of starts in a line.
for(i = 1; i <= 5 ; i++)
{
for(j = 1; j <= i; j++)
cout<<"*";
cout<<endl;
}
• What pattern does the code produce if we replace the first for
statement with the following?
for(i = 5; i >= 1; i--)