You are on page 1of 19

Lecture 5:

Repetition (looping) structures

In repetition, the program repeats particular


statements a certain number of times
based on some condition(s).

There are many situations in which it is necessary to repeat a set of statements.

EX: for each student in a class, the formula for determining the course
grade is the same.
C++ has three repetition (looping) structures that let you repeat statements
over and over until certain conditions are met. These are:
1. while loop
2. do while loop
3. for loop

1. while loop
The general form of the while statement is:
while is a reserved word.
the statement can be one or compound statement between {and}
It is called body of the loop.

Note that the parentheses around the expression are part of the syntax.
The expression acts as a decision maker and is usually a logical expression
and provides an entry condition.
If it initially evaluates to true, the statement executes. Then the expression is
then reevaluated.If it again evaluates to true, the statement executes again.
The statement 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 loops body contains statement(s)
that assure that the expression in the while loop will eventually be false.

Designing while Loops


The body of a while executes only when the expression evaluates to true.
Typically, the expression checks whether a variable(s) (called the loop control
variable (LCV)) satisfies certain conditions.
The LCV must be properly initialized before the while loop, and it should
eventually make the expression evaluate to false by updating or reinitializing
the LCV in the body of the while loop.
If you put a semicolon after the logical expression, the action is empty or null.

Therefore, typically, while loops are written in the following form:

EX1:

int i = 0;
while (i <= 20)
{
cout << i << \t;
i = i + 5;
//change it to print: 0 2 4 6 8 10 and 1 3 5 7 9 and 3 6 9
}
cout << "\n****************************"<<endl;
Sample Run:
0
5
10

15

20

The expression i <= 20 is evaluated first. Because it evaluates to true, the body of
the while loop executes next. The statement i = i + 5; changes the value of i
to 5. After executing the body of while loop, the expression is evaluated
again. Because i is 5, the expression 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 no longer evaluates to true.

Notes:
- When i becomes 25 will not be printed because the entry condition is false.
- If you omit the statement: i = i + 5;
you will have an infinite loop, continually printing rows of zero values.
- You must initialize the loop control variable i before you execute the loop.
Otherwise, you will have an infinite loop, continually printing rows of garbage values.
- If the 2 statements in the body of the loop are interchanged, itll alter the result. Such as:
int i = 0;
while (i <= 20)
{
//a semantic error because the condition is i <= 20 and it produces results for i > 20.
i = i + 5;
cout << i << \t;
}
cout << endl;
The output is:
5
10 15 20

25

//did not print 0

5 minute question
What is the output of this program?
#include <iostream>
using namespace std;
int main()
{

int i = 20;
while (i < 20)
{
cout << i << " ";
i = i + 5;
}
cout << **********<<endl;

//wrong initialization
//initially the loop entry condition evaluates to false
//the body of the while loop will never execute
//there wont be any output
//the value of i remains 20
//the first statement that will be executed

return 0;
}

Case 1: Counter-Controlled while Loops


When a set of statements needs to be executed N times,
You can set up a counter to track how many items will be read.

Before executing the body of the while loop, the counter is compared with N. If
counter < N, the body of the while executes.
The body of the loop continues to execute until the value of counter >= N.
Thus, inside the body of the while loop, the value of counter increments after it
reads a new item.
In this case, the while loop might look like the following:

EX: a program to add SOME entered numbers & find their average (you don't know how many integers)

#include <iostream>
using namespace std;
int main() {
int limit;
//store the number of the entered items
int number;
//variable to store the entered number
double sum = 0.0; //variable to store the sum
int counter = 0;
//loop control variable
MUST BE INITIALIZED BEFORE THE LOOP
cout << "Enter the number of integers in the list: ";
cin >> limit;
cout<<"Enter "<<limit<<"integers: "<<endl; //will be appeared once to the user as it is outside of the loop!
while (counter < limit)
//how many times this loop will be executed?
{
//start while
cin >> number;
sum = sum + number;
//sum+=number;
counter++;
}
//end of while
cout<<"The sum of the " <<limit<< " numbers = "<<sum<<endl; //note printing string vs variable!
double avg = sum/counter;
//declare a new needed variable, avg
cout << "The average = " << avg << endl;
return 0; }

Sample Run:

Enter the number of integers in the list: 12


Enter 12 integers.
8 9 2 3 90 38 56 8 23 89 7 2
The sum of the 12 numbers = 335
The average = 27
This program works as follows:

prompts the user to input the number of data items.


prompts the user to input numbers
The while statement checks the value of counter to determine how many items have been
read. If counter is less than limit, the while loop proceeds for the next iteration. The
first statement in the while body reads the next number and stores it in the variable
number. The next statement updates the value of sum by adding the value of number
to the previous value, and then increments the value of counter by 1. The next
statement outputs the sum of the numbers. The next statements output the average.
The program adds the entered number to the sum of all the numbers entered before the
current number.
The first number read will be added to zero (because sum is initialized to 0.0), giving the
correct sum of the first number.
To find the average, divide sum by counter.

#include <iostream >


#include <string>
using namespace std;
int main(){

string name; int numOfVolunteers; int numOfBoxesSold; double totalNumOfBoxesSold = 0.0;


int counter = 0;
double costOfOneBox;
cout << "Enter the number of volunteers: ";
cin >> numOfVolunteers;
cout << endl;
while (counter < numOfVolunteers)
// < not <= as we started with 0
{
cout << "Enter the volunteer's name and the number of boxes sold: ";
cin >> name >> numOfBoxesSold;
//read 2 variables
cout << endl;
totalNumOfBoxesSold = totalNumOfBoxesSold + numOfBoxesSold;
counter++;
}

cout << "The total number of boxes sold: " << totalNumOfBoxesSold << endl;
cout << "Enter the cost of one box: ";
cin >> costOfOneBox;
cout <<\n The total money by selling cookies: $<< totalNumOfBoxesSold * costOfOneBox;
cout << \n The avg no. of boxes sold by each volunteer: << totalNumOfBoxesSold / counter << endl;
return 0; }

Case 2: Sentinel-Controlled while Loops


You do not know how many entries need to be read, but you may know
that the last entry is a special value, called a sentinel.
In this case, you read the first item before the while loop. If this item does
not equal the sentinel, the body of the while statement executes.
The while loop continues to execute as long as the program has not
read the sentinel.

In this case, a while loop looks like the following:

//A program to read some positive integers and average them, but you do not have a preset number of them.
//Suppose the number -999 marks the end of the entered integers.

#include <iostream>
using namespace std;
const int SENTINEL = -999;
int main() {

int number=0;
//variable to store the number
double sum = 0.0;
//variable to store the sum
int count = 0;
//variable to store the totalnumbers read
cout << "Enter integers ending with " << SENTINEL << endl;
cin >> number;
while (number != SENTINEL)
{

sum = sum + number;


count++;
cin >> number;
}

cout << "The sum of the " << count << " numbers is " << sum << endl;
cout << "The average is " << sum / count << endl;
return 0; }

Case 3: Flag-Controlled while Loops


A flag-controlled while loop uses a bool variable to control the loop.

It takes the following form:

The variable found, which is used to control the execution of the while loop,
is called a flag variable.

EX: The game of Number Guessing


The following program randomly generates an integer greater than or equal to 0
and less than 100.

The program then prompts the user to guess the number. If the user guesses the
number correctly, the program outputs an appropriate message. Otherwise,
the program checks whether the guessed number is less than the random
number. If the guessed number is less than the random number generated by
the program, the program outputs the message Your guess is lower than the
number. Guess again!; otherwise, the program outputs the message Your
guess is higher than the number. Guess again!. The program then prompts
the user to enter another number. The user is prompted to guess the random
number until he enters the correct number.
To generate a random number, use the function rand() of the header file cstdlib.
EX: The expression rand() returns an int value between 0 and 32767.

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int num = rand() % 100;
int guess;
bool isGuessed = false;

//variable to store the random number


//variable to store the number guessed by the user
//boolean variable to control the loop

while (!isGuessed)
{
cout << "Enter an integer greater than or equal to 0 and less than 100: ";
cin >> guess;
if (guess == num)
{
cout << \n You guessed the correct number. << endl;
isGuessed = true;
//to exit from the loop
}
else if (guess < num) cout << "Your guess is lower than the number.\n Guess again! \n;
else cout << "Your guess is higher than the number. \n Guess again! << endl;
}
return 0;
}

Sample Run:
Enter an integer greater than or equal to 0 and less than 100: 45
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 20
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 35
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 28
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 32
You guessed the correct number.

In the previous examples, the expression in the while loop is quite simple
as it is controlled by a single variable.
However, there are situations where the expression in the while may be
more complex.
EX:
The previous program gives as many tries as the user needs to guess the
number. Suppose you want to give the user no more than five tries
to guess the number. If the user does not guess the number correctly
within five tries, then the program outputs the random number
generated by the program as well as a message that you have lost the
game.

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {

int num= rand() % 100;


//variable to store the random number
int guess;
//variable to store the number guessed by the user
bool isGuessed = false;
//boolean variable to control the loop
int noOfGuesses = 0;
while ( (noOfGuesses < 5) && (!isGuessed) ) //2 conditions with 2 loop control variables
{
cout << "Enter an integer greater than or equal to 0 and less than 100: ";
cin >> guess;
noOfGuesses++;
if (guess == num)
{
cout << "\n Winner!. You guessed the correct number." << endl;
isGuessed = true;
}
else if (guess < num) cout <<"Your guess is lower than the number.\n Guess again! \n";
else cout << "Your guess is higher than the number.\n Guess again! \n";
} //end while
if (!isGuessed) cout << "You lose! The correct number is " << num << endl;
return 0; }

for Looping (Repetition) Structure


It is a special form of the while loop.
Its primary purpose is to simplify the writing of counter-controlled loops.

The general form of the for statement is:


for is a reserved word.

The initial statement, loop condition, and update statement are enclosed within ( )

10

The for loop executes as follows:


1. The initial statement executes.
2. The loop condition is evaluated. If the for 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 for loop condition evaluates to false.

The initial statement is the first statement to execute and it is executed only
once.

EX1:
A program to print the first 10 nonnegative integers
#include <iostream>
using namespace std;
int main()
{

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


cout << i << " ";
cout << endl;
return 0;
}
Sample run:
0123456789

The initial statement, i = 0; initializes the int variable i to 0.


Next, the loop condition, i < 10, is evaluated. Because 0 < 10 is true, the print statement
executes and outputs 0.
The update statement, i++, then executes, which sets the value of i to 1.
Once again, the loop condition is evaluated which is still true, and so on. When i becomes 10,
the loop condition evaluates to false, the for loop terminates, and the statement following the
for loop executes.

11

A for loop can have compound statement.


EX2:
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << "Hello!" << endl;
cout << "*" << endl;
}
return 0;
}

Sample run:
Hello!
*
Hello!
*
Hello!
*
Hello!
*
Hello!

Homework:

What will be the output if we omit the {} from the for loop?

EX3:
The action of the following for loop is empty !
for (i = 0; i < 5; i++);
// semantic error.
cout << "*" << endl;
The semicolon at the end of the for statement (before the output statement)
terminates the for loop.

12

Some comments on for loops:


- If the loop condition is initially false, the loop body does not execute.
- The update expression changes the value of the loop control variable which eventually
sets the value of the loop condition to false. The for loop body executes indefinitely
if the loop condition is always true.
- 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 loop, you can omit all three statements (initial statement, loop condition, and
update statement). Such as:
for (;;)
cout << "Hello" << endl;
This is an infinite for loop, continuously printing the word Hello.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
The following are more examples about for loops.

EX4:
#include <iostream>
using namespace std;
int main()
{
for (int i = 10; i >= 1; i--)
cout << " " << i;
cout << endl;
return 0;
}

The output is:


10 9 8 7 6 5 4 3 2 1

13

EX5:

You can increment (or decrement) the loop control variable by any fixed number.
In the following example, the variable is initialized to 1; at the end of the for loop, i is
incremented by 2. to outputs the first 10 positive odd integers.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 20; i = i + 2)
cout << " " << i;
//simple statement
cout << endl;
//printed once only!
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////

The output is:


1 3 5 7 9 11 13 15 17 19

EX6:

Because initially the loop condition is false, nothing happens.


a) Wrong initialization!
#include <iostream>
using namespace std;
int main()
{
for (int i = 10; i <= 9; i++)
cout << i << " ";
cout << endl;
return 0;
}

b) Wrong operator in the condition


#include <iostream>
using namespace std;
int main()
{
for (int i = 9; i >= 10; i--)
cout << i << " ";
cout << endl;
return 0;
}

14

EX7:
The loop condition evaluates to true, so the output statement executes, which outputs 10.
#include <iostream>
using namespace std;
int main()
{
for (int i = 10; i <= 10; i++)
cout << i << " ";
cout << endl;
return 0;
}
//////////////////////////////////////////////////////////////////////////

EX8:
If the loop condition is omitted from the for statement, the loop condition is always true.
This is an infinite loop.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; ; i++)
cout << i << " ";
cout << endl;
return 0;
}

15

EX9:
In this example, a for loop reads five numbers and finds their sum and average.
#include <iostream>
using namespace std;
int main()
{
int i, newNum, sum = 0;
double average;
cout<<"please enter 5 numbers"<<endl;
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;
return 0;
}

The relationship between while loop and for loop


The syntax of the for loop:

is functionally equivalent to this while:

for (initial expression; logical expression; update expression)


statement

initial expression
while (expression)
{
statement
update expression
}

EX:
These for and while loops are equivalent:
for (int i = 0; i < 10; i++) cout << i << " ";
cout << endl;

int i = 0;
while (i < 10)
{
cout << i << " ";
i++;
}
cout << endl;

16

do...while Looping (Repetition) Structure

The general form of a do. . .while statement is as follows:


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 is true, the statement executes.


To avoid an infinite loop:
you must make sure that the loop body contains a statement
that ultimately makes the expression false and assures that it
exits properly.

EX:
#include <iostream>
using namespace std;
int main()

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

}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

The output is:


0 5 10 15 20

17

The difference between the 3 loop structures


In a while and for loop, the loop condition is evaluated before executing the
body of the loop. Therefore, while and for loops are called pretest loops.
On the other hand, the loop condition in a do. . .while loop is evaluated after
executing the body of the loop. Therefore, do. . .while loops are called
posttest loops.

Because the while and for loops both have entry conditions, these loops
may never activate.
The do...while loop, on the other hand, has an exit condition and therefore
always executes the statement at least once.

Compare between the following two codes:


a. #include <iostream>
using namespace std;
int main()
{
int i = 11;
while (i <= 10)
{
cout << i << " ";
i = i + 5;
}
cout << endl;
return 0;
}

b. #include <iostream>
using namespace std;
int main()
{
int i = 11;
do
{
cout << i << " ";
i = i + 5;
}
while (i <= 10);
cout << endl;
return 0;
}

This while loop produces nothing.

This loop outputs the number 11


and also changes the value of i to 16.

18

Choosing the Right Looping Structure


All three loops have their place in C++.
If you know, or the program can determine in advance, the number of
repetitions needed, the for loop is the correct choice.

If you do not know, and the program cannot determine in advance the
number of repetitions needed, and it could be zero, the while loop is
the right choice.

If you do not know, and the program cannot determine in advance the
number of repetitions needed, and it is at least one, the do...while
loop is the right choice.

19

You might also like