Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

ENGR 1200U Introduction to Programming Lecture 13 Control Structures: Repetition Part II (Chapter 4)

Dr. Eyhab Al-Masri

1992-2012 by Pearson Education, Inc. & John Wiley & Sons Some portions are adopted from C++ for Everyone by Horstmann

Consider the following example


rem
before after L1 after L2 after L3 after L4

int number(159); int sum=0; while (number>0) { int rem=number%10; sum=sum+rem; number=number/10; } cout<<"Thesumis:" <<sum<<endl;

sum

number

N/A 9 5 1

0 9 14 15

159 15 1 0

will not execute a 4th time

The sum is: 15


ENGR 1200U Winter 2013 - UOIT

It often happens that you want to execute a sequence of statements a given number of times. You can use a while loop, controlled by a counter
int counter=1; while (counter<=10) { cout<<counter<<endl; counter++; }
//initializecounter //checkcounter //printcountervalue //updatecountervalue

Sincethislooptypeiscommon,thereis aspecialformforit,calledfor loop (alsocalledCounterControlledLoop)


ENGR 1200U Winter 2013 - UOIT

int counter=1; while (counter<=10) { cout<<counter<<endl; counter++; }

//initializecounter //checkcounter //printcountervalue //updatecountervalue

for (int counter=1;counter<=10;counter++) { cout<<counter<<endl; }

ENGR 1200U Winter 2013 - UOIT

initialization expression

condition expression

Update expression

for (int counter=1;counter<=10;counter++) { cout<<counter<<endl; }


initialization condition

update

int counter=1; while (counter<=10) { cout<<counter<<endl; counter++; }

//initializecounter //checkcounter //printcountervalue //updatecountervalue

ENGR 1200U Winter 2013 - UOIT

initialization expression

condition expression

Update expression

for (int counter=1;counter<=10;counter++) { cout<<counter<<endl; } initializationcode: codethathappensonce,beforethecheckismade usedtosetuphowmanytimesthestatementswill happen Loopvariablecreatedhere

ENGR 1200U Winter 2013 - UOIT

initialization expression

condition expression

Update expression

for (int counter=1;counter<=10;counter++) { cout<<counter<<endl; } conditioncode: teststoseeiftheloopisdone Whentestisfalse,theforstatementisoverandwe movetothenextstatement

ENGR 1200U Winter 2013 - UOIT

initialization expression

condition expression

Update expression

for (int counter=1;counter<=10;counter++) { cout<<counter<<endl; } updatecode: causestheconditiontoeventuallybecomefalse mainlyusedtoincrementordecrementtheloop variable

ENGR 1200U Winter 2013 - UOIT

for (int counter=1;counter<=10;counter++) { cout<<counter<<endl; }

ENGR 1200U Winter 2013 - UOIT

A for loop can count down instead of up


for (int counter=10;counter>=0;counter) { cout<<counter<<endl; }

The increment or decrement can be in steps of more than 1


for (int counter=0;counter<=10;counter+=2) { cout<<counter<<endl; }

ENGR 1200U Winter 2013 - UOIT

int main() { const double RATE=5; const double INITIAL_BALANCE=10000; double balance=INITIAL_BALANCE; int number_of_years; cout <<"Enterthenumberofyears:"; cin >>number_of_years;

Problem: Print the balance of our savings account over a period of years Solution: Use for loop

cout <<fixed<<setprecision(2); cout <<setw(4)<<"Year" <<setw(10)<<"Balance" <<endl; for (int year=1;year<=number_of_years;year++) { double interest=balance*(RATE/100); balance=balance+interest; cout <<setw(4)<<year<<setw(10)<<balance<<endl; } Algorithm: return 0; }
for (int year=1;year<=number_of_years;year++) { //updatebalance //printyearandbalance }
C++ for Everyone by Cay Horstman

ENGR 1200U Winter 2013 - UOIT

What is the output of the following for loop?


for (int i=0;i<=5;i++) cout<<i<<"";

output

012345

loop executes six times, not five!


ENGR 1200U Winter 2013 - UOIT

What is the output of the following for loop?


for (int i=5;i<=0;i++) cout<<i<<"";

output

Again, loop executes six times


ENGR 1200U Winter 2013 - UOIT

What is the output of the following for loop?


for (int i=0;i<9;i+=2) cout<<i<<"";

output

02468
There are 5 iterations

ENGR 1200U Winter 2013 - UOIT

What is the output of the following for loop?


for (int i=0;i!=9;i+=2) cout<<i<<"";

output

024681012
infinite loop; never ends

ENGR 1200U Winter 2013 - UOIT

Sometimes you want to execute the body of a loop at least once and perform the loop test after the body is executed. The do/while loop serves this purpose.
do {
//statements Use the do/while loop when statements must be executed before any knowledge of the condition

}while(condition);

Thedo/whileloophasitscondition testedonlyafter atleastoneexecution ofthestatements

ENGR 1200U Winter 2013 - UOIT

At what instances would you require something to take place before executing a loop?
Prompttheuserforinput

Usershouldenteravalue<100 andprocessingmustnotcontinue untilavalueisentered

ENGR 1200U Winter 2013 - UOIT

C++ for Everyone by Cay Horstman

Example 1
int value; do { cout<<"Enteravalue<100:"; cin>>value; } while (value>=100);

Userwillseesameprompteach timeaslongastheconditionis true

ENGR 1200U Winter 2013 - UOIT

C++ for Everyone by Cay Horstman

ENGR 1200U Winter 2013 - UOIT

C++ for Everyone by Cay Horstman

Loops are often required for reading data from the keyboard or from a data file There are three common loop forms
1. CounterControlled Loop 2. SentinelControlled Loop 3. EndOfData Loop

ENGR 1200U Winter 2013 - UOIT

10

Used for reading input data if the number of data values is known before the data are entered
Number of data values is stored in a counter

counter is often used to control the number of iterations can be easily implemented using the while or for loops

ENGR 1200U Winter 2013 - UOIT

Used for reading input data if a special data value exists that can be used to indicate the end of the data
When reading a sequence of inputs, you often need a method to indicate end of the sequence A value that serves as a signal for termination is called a sentinel

ENGR 1200U Winter 2013 - UOIT

11

Assume we would like compute the average of a set of salary values. We will use -1 as a sentinel.

Inside the loop, we read an input. If the input is not -1, we process it. To compute the average, we need the total sum of all salaries, and the number of inputs.
while (...) { cin>>salary; if (salary!=1) { sum=sum+salary; count++; } } while (salary!=1) { cin >>salary; if (salary!=1) { sum=sum+salary; count++; } }

ENGR 1200U Winter 2013 - UOIT

There is one problem: when the loop is entered the first time, no data value have been read.
Hence, no initial value for salary
doublesalary=0; while (salary!=1) { cin>>salary; if (salary!=1) { sum=sum+salary; count++; } }

do { cin>>salary; if (salary!=1) { sum=sum+salary; count++; } }while (salary!=1);

ENGR 1200U Winter 2013 - UOIT

12

Is the most flexible loop for reading input data It is structured to continue executing the statements inside the loop while new data are available
No prior knowledge values is required of data

No sentinel value is required

ENGR 1200U Winter 2013 - UOIT

13

You might also like