Chapter 5 control structures ii repetition
Download
1 / 58

CHAPTER 5 CONTROL STRUCTURES II (Repetition) - PowerPoint PPT Presentation


  • 118 Views
  • Uploaded on

CHAPTER 5 CONTROL STRUCTURES II (Repetition). 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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' CHAPTER 5 CONTROL STRUCTURES II (Repetition)' - sylvester-riddle


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Chapter 5 control structures ii repetition

CHAPTER 5CONTROL STRUCTURES II(Repetition)


THE whileLOOPING (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<<" "; //Line 3

i = i + 5; //Line 4

}

Output:

0 5 10 15 20


Example 5-2

i = 20; //Line 1

while(i < 20) //Line 2

{

cout<<i<<" "; //Line 3

i = i + 5; //Line 4

}

Here no values will be output.


Case 2: Sentinel ControlledwhileLoop

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; // variable to store the number

int sum = 0; // variable to store the sum

int count = 0; // 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) //Line 3

{

sum = sum + number; //Line 4

count++; //Line 5

cin>>number; //Line 6

}


cout<<"Line 7: The sum of "<<count

<<" numbers is "<<sum<<endl; //Line 7

if(count != 0) //Line 8

cout<<"Line 9: The average is "

<<sum / count<<endl; //Line 9

else//Line 10

cout<<"Line 11: No input."<<endl; //Line 11

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


Case 3: Flag-Controlled whileLoops

  • 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 variablereturns 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 infile;

char ch;

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 thewhilestatementistrue.

  • When the program reads past the end of the input file, the expression

    infile.eof()

    becomestrueandso the expression

    !infile.eof()

    inthewhilestatement will becomefalseand the loop terminates.


PROGRAMMING EXAMPLE: CHECKING ACCOUNT BALANCE file, the expression

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 the account balance at the beginning of the month. :

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 account balance at the beginning of the month.

  • 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. you need to process each entry that contains the transaction code and transaction amount.

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 you need to process each entry that contains the transaction code and transaction amount.

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

//amountdeposited

numberOfDeposits //variable to store the

//number of deposits

amountWithdrawn //variable to store total

//amountwithdrawn

numberOfWithdrawals //variable to store number

//of withdrawals

interestPaid //variable to store interest

//amountpaid


int you need to process each entry that contains the transaction code and transaction amount. acctNumber;

double beginningBalance;

double accountBalance;

double amountDeposited;

int numberOfDeposits;

double amountWithdrawn;

int numberOfWithdrawals;

double interestPaid;

char transactionCode;

double transactionAmount;

bool isServiceCharged;

ifstream infile; //input file stream variable

ofstream outfile; //output file stream variable


Named Constants you need to process each entry that contains the transaction code and transaction amount.

const double minimumBalance = 1000.00;

const double serviceCharge = 25.00;


1. Declare the variables. you need to process each entry that contains the transaction code and transaction amount. Declare variables as discussed previously.

2. Initialize the variables.

  • Initialize the variables amountDeposited, numberOfDepositsamountWithdrawn, 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"); you need to process each entry that contains the transaction code and transaction amount. //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. you need to process each entry that contains the transaction code and transaction amount. Get the account number and starting balance.

infile>>acctNumber>>beginningBalance;

4. Getthe transaction code and transaction amount.

infile>>transactionCode>>transactionAmount;


5. you need to process each entry that contains the transaction code and transaction amount. Analyze thetransaction 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 you need to process each entry that contains the transaction code and transaction amount. '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 you need to process each entry that contains the transaction code and transaction amount. . 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. Printthe result: This is accomplished by using output statements.


Main Algorithm you need to process each entry that contains the transaction code and transaction amount.

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) you need to process each entry that contains the transaction code and transaction amount.

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.


//******************************************************* you need to process each entry that contains the transaction code and transaction amount.

// 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 //Step 1

int acctNumber;

double beginningBalance;

double accountBalance;

double amountDeposited = 0.0;

int numberOfDeposits = 0;


double you need to process each entry that contains the transaction code and transaction amount. 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"); you need to process each entry that contains the transaction code and transaction amount. //Step 4

outfile<<fixed<<showpoint; //Step 5

outfile<<setprecision(2); //Step 5

cout<<"Processing data"<<endl;

infile>>acctNumber>>beginningBalance; //Step 6

accountBalance = beginningBalance; //Step 7

infile>>transactionCode>>transactionAmount;

//Step 8


while you need to process each entry that contains the transaction code and transaction amount. (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 you need to process each entry that contains the transaction code and transaction amount. '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; you need to process each entry that contains the transaction code and transaction amount.

}//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 you need to process each entry that contains the transaction code and transaction amount. (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: you need to process each entry that contains the transaction code and transaction amount. (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


THE you need to process each entry that contains the transaction code and transaction amount. forLOOPING (REPETITION) STRUCTURE

The general form of the for statement is

for(initial statement; loop condition;

update statement)

statement

  • The initialstatement, loopcondition and updatestatement (called for loop control statements) that are enclosed with in the parentheses controls the body (the statement) of the for statement.


  • The you need to process each entry that contains the transaction code and transaction amount. for loop executes as follows:

    1. The initialstatement executes.

    2. The loop condition is evaluated.

    a. If the loopcondition evaluates to true

    i. Execute the for loop statement.

    ii. Execute the updatestatement (the third expression in the

    parentheses).

    3. Repeat Step 2 until the loopcondition evaluates to false.

  • The initialstatement 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 initialstatement in the for loop is the first statement to be executed and is executed only once.


Example 5-6 you need to process each entry that contains the transaction code and transaction amount.

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 you need to process each entry that contains the transaction code and transaction amount.

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. you need to process each entry that contains the transaction code and transaction amount.

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 you need to process each entry that contains the transaction code and transaction amount. for loop executes five empty statements:

for(i = 1; i <= 5; i++); //Line 1

cout<<"*"<<endl; //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 you need to process each entry that contains the transaction code and transaction amount. 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 you need to process each entry that contains the transaction code and transaction amount. for statement, you can omit all three statements—initialstatement, loopcondition, and updatestatement. The following is a legal for loop:

    for(;;)

    cout<<"Hello"<<endl;


THE you need to process each entry that contains the transaction code and transaction amount. do…whileLOOPING (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 expressionfalse 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 that the loop body contains a statement that ultimately makes the

do

{

cout<<i<<" ";

i = i + 5;

}

while(i <= 20);

The output is:

0 5 10 15 20


  • Because the that the loop body contains a statement that ultimately makes 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 that the loop body contains a statement that ultimately makes the : 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.


ad