0% found this document useful (0 votes)
547 views69 pages

C++ Loop Structures Guide

This document discusses repetition structures in C++, specifically various types of looping structures using while loops. It covers counter-controlled, sentinel-controlled, and flag-controlled while loops. It also discusses end-of-file controlled while loops, which are used when the number of iterations is unknown. Examples are provided for each type of loop. Nested control structures and compound expressions that can be used with while loops are also mentioned.

Uploaded by

Syed Samsamuddin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
547 views69 pages

C++ Loop Structures Guide

This document discusses repetition structures in C++, specifically various types of looping structures using while loops. It covers counter-controlled, sentinel-controlled, and flag-controlled while loops. It also discusses end-of-file controlled while loops, which are used when the number of iterations is unknown. Examples are provided for each type of loop. Nested control structures and compound expressions that can be used with while loops are also mentioned.

Uploaded by

Syed Samsamuddin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 69

Chapter 5

Control Structures II (Repetition)

Outline
1.

Why Is Repetition Needed?

2.

while Looping (Repetition) Structure

3.

for Looping (Repetition) Structure

4.

dowhile Looping (Repetition) Structure

5.

break and continue Statements

6.

Nested Control Structures

7.

Exercises

1. Why is Repetition Needed?

Suppose we want to find the average of five numbers.

If we want to calculate the average of 100 numbers?

double sum, average, num1, num2, num3, num4, num5;


cout << "Enter 5 double numbers: " << endl;
cin >> num1 >> num2 >> num3 >> num4 >> num5;
sum = 0;
sum = sum + num1;
sum = sum + num2;
sum = sum + num3;
sum = sum + num4;
sum = sum + num5;
average = sum/5;

2. while Looping (Repetition) Structure

Syntax:
while (expression)
statement // body of the loop

expression

false

true

statement

2. while Looping (Repetition) Structure: Example


int i = 0;
while(i <= 20)

int i = 0;

while(i <= 20)

cout << i << " ";

cout << i << " ";

i = i + 5; //i += 5;
}

Output

Output

0 5 10 15 20

000000000000
000000000000
0 0 0 0 0 0 0 0 0 0 0

2. while Looping (Repetition) Structure: Example


int i ; // i is not initialized
while(i <= 20)
{
cout << i << " ";
i = i + 5; //i += 5;
}

Output

2. while Looping (Repetition) Structure: Example


int i = 0 ;
while(i <= 20)
{
i = i + 5; //i += 5;
cout << i << " ";
}

Output
5 10 15 20 25

2. while Looping (Repetition) Structure: design


// initialize the loop control variable(s): LCV
while(expression) //expression tests the LCV
{
.
.
.
//update the loop control variable(s)
.
.
.
}

2. while Looping : case1: Counter-Controlled while Loops


A while loop can be used as a counter if we know how many times a
statement is to be executed.
counter = 0;
while(counter < N)
{
.
.
.
counter++;
.
.
.
}

2. while Looping : case1: Counter-Controlled while Loops

Example
Suppose the input is:
8 9 2 3 90 38 56 8 23 89 7 2 8 3 8
Write a program to add these numbers and find
their average (use a counter while loop).

2. while Looping : case1: Counter-Controlled while Loops


#include<iostream>
using namespace std;
int main()
{
int limit, number, sum = 0, counter = 0;
cout<<"Enter the number of integers in the list: ";
cin>>limit;
cout<<"Enter "<<limit<<" numbers: ";
while(counter<limit)
{
cin>>number;
sum += number;
counter++;
}
cout<<"The sum of the "<<limit<<" numbers = "<<sum<<endl;
if(counter != 0)
cout<<"The average = "<<sum/counter<<endl;
else
cout<<"No input"<<endl;
return 0;
}

2. while Looping : case2: Sentinel-Controlled while Loops

You do not know how many


pieces

of

data

(or

entries)

needed to be read.
But, you may know that the
last entry is a special value
(sentinel).

cin >> variable;


while(variable != sentinel)
{
.
.
.
cin >> variable;
.
.
.
}

2. while Looping : case2: Sentinel-Controlled while Loops

Example
Suppose you want to read some positive
integers and average them, but you do not have
a preset number of data item in mind. Suppose
the number -999 marks the end of the data.

2. while Looping : case2: Sentinel-Controlled while Loops


#include<iostream>
using namespace std;
const int SENTINEL = -999;
int main()
{
int number, sum = 0, count = 0;
cout<<"Enter integers ending with "<<SENTINEL<<": ";
cin>>number;
while(number != SENTINEL)
{
sum += number;
count++;
cin>>number;
}
cout<<"The sum of the "<<count<<" numbers = "<<sum<<endl;
if(count != 0)
cout<<"The average = "<<sum/count<<endl;
else
cout<<"No input"<<endl;
return 0;
}

2. while Looping : case3: Flag-Controlled while Loops

A flag-controlled while loop


uses a boolean variable to
control

the

loop

(the

boolean variable is called


flag variable).

bool found = false;


while(!found)
{
.
.
.
if (expression)
found = true;
.
.
.
}

2. while Looping : case3: Flag-Controlled while Loops


Example
Write a program to generate randomly a number
between 0 and 100. use a flag-controlled while loop to
prompt the user to guess the number. Your program
should display one of the messages:
You guessed correctly the number
Your guess is higher than the number. Guess again!
Your guess is lower than the number. Guess again!

2. while Looping : case3: Flag-Controlled while Loops


#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int num, guess;
bool isGuessed = false;
num = (rand() + time(0)) %100;
// while loop
return 0;
}

2. while Looping : case3: Flag-Controlled while Loops

while(!isGuessed)
{
cout << "Enter an integer between 0 and 100: ";
cin >> guess;
if(guess == num)
{
cout<<"You guessed the correct number."<<endl;
isGuessed = true;
}
else if(guess < num)
cout<<"You guessc is lower than the number.
<<"\n Guess again!"<<endl;
else
cout<<"You guessc is higher than the number.
<<"\n Guess again!"<<endl;
}

2. while Looping : case4: EOF-Controlled while Loops

If the sentinel and the number of iterations are not known, we use
an EOF (End Of File)-controlled while loop.

The input stream variables (such as cin) can be used to control


the end of the input data.

The input stream variables return a value after reading data:

If the program has reached the end of the input data (eg. the user
presses enter), the input stream variable returns the logical value
false.

If the program reads any faulty data (such as a char into an int), the
input stream enters the fail state (any further I/O using that that
stream operations have no effect).

2. while Looping : case4: EOF-Controlled while Loops


cin >> variable;
while(cin)
{
.
.
.
cin >> variable;
.
.
.
}

2. while Looping : case4: EOF-Controlled while Loops

The C++ function eof() can be used with an input stream variable
to determine the end-of-file status.

Syntax: istreamVar.eof();

ifstream infile;
infile.eof() is a boolean value (true or false)

2. while Looping : case4: EOF-Controlled while Loops


#include<fstream>
.
.
.
ifstream infile;
char ch;
infile.open("inputDat.dat");
infile.get(ch);
while(!infile.eof()) //while(infile.eof()==false)
{
cout << ch;
infile.get(ch);
}

2. while Looping : case4: EOF-Controlled while Loops

Example
A local bank in your town is looking for someone to write a program
that calculates a customers 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

First line: account # and account

D 1200.00

balance at the beginning of the month.

W 75.00

W or w: withdrawal

I 120.74

D or d: deposit

I or i: interest paid by the bank

2. while Looping : case4: EOF-Controlled while Loops


The program updates the balance after each transaction.
During a month, if at any time the balance goes below
BD1000.00, a BD25.00 service fee is charged (max 1 time/month).
Input: A file consisting of data in the previous form.
Output (to be stored in a file):

Account Number: 467343


Beginning Balance: BD23750.40
Ending Balance: BD 24611.49
Interest Paid: BD 366.24
Amount Deposited: BD 2230.50
Number of Deposits: 3
Amount Withdrawn: BD 1735.65
Number of Withdrawals: 6

2. while Looping : case4: EOF-Controlled while Loops

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.

2. while Looping : case4: EOF-Controlled while Loops

Algorithm: steps 1 & 2


const double MINIMUM_BALANCE = 1000.00;
const double SERVICE_CHARGE = 25.00;
int acctNumber;
double beginningBalance;
double accountBalance;
double amountDeposited = 0.0;
int numberOfDeposists = 0;
double amountWithdrawan = 0.0;

int numberOfWithdrawals =0;


double interestPaid = 0.0;
char transactioCode;
double transactionAmount;
bool isServiceCharged = false;

2. while Looping : case4: EOF-Controlled while Loops

Algorithm: steps 3 & 4


3.Get the account number and starting balance:
infile >> acctNumber >> beginningBalance;
4.Get the transaction code and transaction amount
infile >> transactionCode >> transactionAmount;

2. while Looping : case4: EOF-Controlled while Loops


Algorithm: step 5 (use swicth statement)
Analyze the transaction code and update the appropriate variables
If transactionCode is D or d: update accountBalance and amountDeposited by
adding transactionAmount, and increment numberOfDeposits.
If transactionCode is I or i: update accountBalance and intersetPaid by adding
transactionAmount.
If transactionCode is W or w: update accountBalance/amountWithdrawan by
subtracting/adding transactionAmount, increment numberOfWithdrawals, and if the
account balance is below the minimum and service charges have not been applied,
subtract the service charge from the account balance and mark the service charges
as having been applied.

2. while Looping : case4: EOF-Controlled while Loops

Algorithm: steps 6 & 7


6.Repeat steps 4 and 5 until there is no more data.
Because the number of entries in the input file is not known,
the program needs and EOF-controlled while loop.
7.Print the result to a file: output statement.

2. while Looping : case4: EOF-Controlled while Loops

Program

2. while Looping : Compound expressions


Example
Write a program to generate randomly a number between 0 and
100. use a flag-controlled while loop to prompt the user to guess the
number. Your program should display one of the messages:
You guessed correctly the number
Your guess is higher than the number. Guess again!
Your guess is lower than the number. Guess again!
Your program should terminate if the user does not guess the
number correctly within five tries (display the correct number as well
as a message You have lost the game.)

2. while Looping : Compound expressions


while(noOfGuesses < 5 && !isGuessed)
{
cout << "Enter an integer between 0 and 100: ";
cin >> guess;
noOfGuesses++;
if(guess == num)
{
cout<<"You guessed the correct number."<<endl;
isGuessed = true;
}
else if(guess < num)
cout<<"You guessc is lower than the number.
<<"\n Guess again!"<<endl;
else
cout<<"You guessc is higher than the number.
<<"\n Guess again!"<<endl;
}
if(!isGuessed)
{ cout << "You have lost the game."<<endl;
cout << "The correct number is: "<<num<<endl; }

3. for Looping (Repetition) Structure


The while loop is general enough to implement most forms of
repetitions.
The C++ for looping structure is a special form of the while loop.
The for loop (indexed or counted for loop) is used to simplify the
counter-controlled loops.

for (initial statement; loop condition; update statement)


statement

3. for Looping (Repetition) Structure


The for loop executes as follows:
1. The initial statement executes.
2. The loop condition is evaluated. If the loop condition evaluates to
true:
a) Execute the for loop statement.
b) Execute the update statement (the 3rd expression in
parentheses).
3. Repeat Step 2 until the loop condition evaluates to false.

3. for Looping (Repetition) Structure


Example 1

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

Output
0123456789

3. for Looping (Repetition) Structure


Example 2

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

Output
5

3. for Looping (Repetition) Structure


Example 3
int i;
for(i = 1; i < 5; i++)
{
cout << Hello << i ;
cout << endl;
}

Output
Hello 1
Hello 2
Hello 3
Hello 4

3. for Looping (Repetition) Structure


Example 4

Output
Hello
for(;;)
cout << Hello << endl ;

Hello
Hello
Hello

3. for Looping (Repetition) Structure


Example 5

for(int i = 1; i <= 20 ; i = i + 2)
cout << i << ;

Output
1 3 5 7 9 11 13 15 17 19

3. for Looping (Repetition) Structure


Example 6

for(int i = 10; i >= 1 ; i--)


cout << i << ;

Output
10 9 8 7 6 5 4 3 2 1

3. for Looping (Repetition) Structure


Example 7

for(int i = 10; i <= 9 ; i++)


cout << i << ;

Output

3. for Looping (Repetition) Structure


Example 8

for(int i = 1; i <= 9 ; i++);


cout << << i;

Output
10

3. for Looping (Repetition) Structure


Exercise 1
1. Write a for loop to calculate the sum of the first 10
integers starting from 1.
2. Modify the previous for loop to calculate the sum of
the first n integers starting from 1.
int s = 0;
for(int i = 1; i <= 10 ; i++)
s += i;
cout << s << endl;

int s = 0, n;
cin >> n;
for(int i = 1; i <= n ; i++)
s += i;
cout << s << endl;

3. for Looping (Repetition) Structure

Exercise 2
Write a C++ code to:
A. Prompt the user to enter n integers (n to be read
also).
B. Display the number of even numbers and the
number of odd numbers.

3. for Looping (Repetition) Structure


#include<iostream>
using namespace std;
Solution
void main()
{
int even = 0, odd = 0, i, n, num;
cout << "Enter the number of integers: " ;
cin >> n;
cout << "Enter the " << n << " integers: " ;
for(i = 0; i < n; i++)
{
cin >> num;
if(num % 2 ==0)
even++;
else
odd++;
}
cout << even << even numbers. << endl;
cout << odd<< odd numbers. << endl;
}

Exercise 2

4. dowhile Looping (Repetition) Structure

The statement executes first, and then


the expression is evaluated.

do
statement
while (expression);

The statement is to be executed at least


one time (even if the expression is false).
The variables of the expression must be
updated to avoid infinite loop

4. dowhile Looping (Repetition) Structure

Example 1
int i = 0;
do
{
cout << i << " ";
i = i + 5;
}
while (i <= 20);

Output
0 5 10 15 20

4. dowhile Looping (Repetition) Structure

Example 2
int i = 11;
while (i <= 10)
{
cout << i << " ";
i = i + 5;
}

int i = 11;
do
{
cout << i << " ";
i = i + 5;
}
while (i <= 10);

Output

Output
11

4. dowhile Looping (Repetition) Structure

Example 3

Write a C++ code using do-while loop to read


an integer number and add its digits.

4. dowhile Looping (Repetition) Structure

Solution Example 3
int num, temp, sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
temp = num;
do
{
sum = sum + temp%10;
temp = temp/10;
}
while(temp > 0);
cout << The sum of digits of << num << " = << sum << endl;

Choosing the Right Looping Structure


If the number of repetitions is known, the for loop is the correct
choice.
If the number of repetitions is not known, and it could be zero,
the while loop is the right choice.
If the number of repetitions is not known, and it is at least one,
the dowhile loop is the right choice.

5. break and continue Statements


The break statement can be used inside a loop to provide an
immediate exit.
The break statement can eliminate the use of certain (flag)
variables.
After the break statement executes, the program continues to
execute with the first statement after the structure
The break statement is used for two purposes:
To exit early from a loop.
To skip the reminder of the switch structure.

5. break and continue Statements


Find the sum of positive numbers and stop when a negative number is found.

int sum = 0, num;


bool isNegative = false;
cin >> num;
while(cin && !isNegative)
{
if(n um< 0)
isNegative = true;
else
{
sum = sum + num;
cin >> num;
}
}

int sum = 0, num;


cin >> num;
while(cin)
{
if(num < 0)
break;
sum = sum + num;
cin >> num;
}

5. break and continue Statements


The continue statement is used in while, for, and dowhile
structures.
The continue statement is executed in a loop to skip its
remaining statements and proceeds with the next iteration.
In a while and dowhile structures, the expression is evaluated
immediately after the continue statement.
In a for loop, the update statement is executed after the continue
statement.

5. break and continue Statements


Example
Modify the program in slide 53, so that it adds the positive numbers
and discards the negative numbers (read the next number rather
then terminate).

int sum = 0, num;


cin >> num;
while(cin)
{
if(num < 0)
{
cin >> num;
continue;
}
sum = sum + num;
cin >> num;
}

6. Nested Control Structures


Write a nested for loop to create the following pattern:
*
**
***
int i, j;
****
for(i = 1; i<= 5; i++)
*****

for(j = 1; j<= i; j++)


cout << "*";
cout << endl;
}

6. Nested Control Structures


What pattern does the previous code produce if you
replace the for statement, in line 1, with the following?

for(i = 5; i>= 1; i--)

Answer:

*****
****
***
**
*

6. Nested Control Structures


Write a nested for loop to create the following grid numbers
12345
23456
34567
Solution 1
Solution 2
45678
56789

int i, j;
for(i = 1; i<= 5; i++)
{
for(j = 0; j<= 4; j++)
cout << i+j << ;
cout << endl;
}

int i, j;
for(i = 1; i<= 5; i++)
{
for(j = i; j<= i + 4; j++)
cout << j << ;
cout << endl;
}

6. Nested Control Structures


Consider the following data saved in a file.
65 78 65 89 25 98 -999
87 34 89 99 26 78 64 34 -999
23 99 98 97 26 78 100 63 87 23 -999
62 35 78 12 19 -999
Where the -999 in each line is a sentinel to be ignored.
Write a nested loop to find the sum of the numbers in
each line and out put the sum.

6. Nested Control Structures


Outer while loop
Proceed the 4 lines and output the sum of each line
counter = 0;
while(counter < 4)
{
// process the line
// output the sum
counter++
}

6. Nested Control Structures


Inner while loop
Add the numbers of a line
sum = 0;
infile >> num;
while(num != 999)
{
sum = sum + num;
infile >> num;
}

6. Nested Control Structures


Solution
int counter = 0, sum;
while(counter < 4)
{
sum = 0;
infile >> num;
while(num != -999)
{
sum = sum + num;
infile >> num;
}
cout << "Line " << counter + 1 << ": Sum = " << sum << endl;
counter ++;
}

7. Exercises
What is the output from the following code?
int i=0, j=6;
while (++i < j)
{
cout << j-i <<" ";
cout << endl;
i++;
}

7. Exercises

int i, j=10;
for (i=1; i<= 5; i++)
cout << i*j << "-";
cout << "Done!\n";

7. Exercises
int j=0;
double y=3.5;
do
{
j=static_cast<int>(y);
y=y+0.5;
cout<< j << \t;
} while (j<5);

7. Exercises
A Telephone Company wants to know how many fixed
and mobile lines are currently in the services. The fixed
line number consists of eight (8) digits that begins with
17 while the mobile line number consists of eight (8)
digits that begins with 39. Write a program that allows
the user to enter telephone numbers until a negative
number is entered. Your program should count and
output the number of fixed and mobile lines.

7. Exercises
#include<iostream>
using namespace std;
int main()
{
bool flag = false;
int x, f = 0, m = 0;
while(!flag)
{
cin>>x;
if(x/1000000 == 17)
f++;
else if(x/1000000 == 39)
m++;
else if(x<0)
flag = true;
}
cout<<"# mobile users = "<<m<<endl;
cout<<"# fix users = "<<f<<endl;
return 0;
}

7. Exercises
Consider the following data:
Ali 65 78 65 89 25 98 -999
Marwa 87 34 89 97 26 78 100 63 87 23 -999
Hussain 23 99 98 97 26 78 100 63 87 23 -999
Maryam 62 35 78 99 12 93 19 -999

The number -999 at the end of each line is a sentinel.


The objective is to display the number average of each
line. We assume that the data is to be read from a file
with unknown size (the number of lines is not known)

7. Exercises

int sum, num, count,


average;
string name;
ifstream infile;
infile.open("in.txt");

infile>>name;
while(infile)
{
sum = 0;
count = 0;
infile >> num;
while(num != -999)
{
sum = sum + num;
count++;
infile >> num;
}
if(count != 0)
average = sum / count;
cout << name << " : " << average<<endl;
infile >> name;
}

You might also like