Download - CS503 Lec5
-
8/16/2019 CS503 Lec5
1/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
-
8/16/2019 CS503 Lec5
2/19
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 evaluatesto 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 loop’s 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:
-
8/16/2019 CS503 Lec5
3/19
EX1:
int i = 0;
while (i
-
8/16/2019 CS503 Lec5
4/19
5 minute question
What is the output of this program?
#include
using namespace std;
int main()
{
int i = 20; //wrong initialization
while (i < 20) //initially the loop entry condition evaluates to false
{ //the body of the while loop will never execute
cout
-
8/16/2019 CS503 Lec5
5/19
EX:a program to add SOME entered numbers& find their average (you don't know how many integers)
#include
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 > limit;
cout
-
8/16/2019 CS503 Lec5
6/19
-
8/16/2019 CS503 Lec5
7/19
//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
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 > number;
}
cout
-
8/16/2019 CS503 Lec5
8/19
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.
nc u e < ostream>
#include
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
while (!isGuessed)
{
cout > guess;
if (guess == num)
{
cout
-
8/16/2019 CS503 Lec5
9/19
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 simpleas it is controlled by a single variable.
However, there are situations where the expression in the while may bemore complex.
EX:
The previous program gives as many tries as the user needs to guess thenumber. Suppose you want to give the user no more than five triesto guess the number. If the user does not guess the number correctlywithin five tries, then the program outputs the random numbergenerated by the program as well as a message that you have lost the
game.
-
8/16/2019 CS503 Lec5
10/19
#include
#include
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 > guess;
noOfGuesses++;
if (guess == num)
{
cout
-
8/16/2019 CS503 Lec5
11/19
The for loop executes as follows:
1. The initial statement executes.
2. The loop condition is evaluated. If the for loop conditionevaluates 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 onl
once.
EX1:
A program to print the first 10 nonnegative integers
#include
using namespace std;
int main()
{
for (int i = 0; i < 10; i++)
cout
-
8/16/2019 CS503 Lec5
12/19
A for loop can have compound statement.
EX2:
#include
using namespace std;
int main()
{
for (int i = 1; i
-
8/16/2019 CS503 Lec5
13/19
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 indefinitelyif 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
-
8/16/2019 CS503 Lec5
14/19
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
using namespace std;
int main()
{
for (int i = 1; i
-
8/16/2019 CS503 Lec5
15/19
EX7:
The loop condition evaluates to true, so the output statement executes, which outputs 10.
#include
using namespace std;
int main()
{
for (int i = 10; i
-
8/16/2019 CS503 Lec5
16/19
EX9:
In this example, a for loop reads five numbers and finds their sum and average.
#include
using namespace std;
int main(){
int i, newNum, sum = 0;
double average;
cout
-
8/16/2019 CS503 Lec5
17/19
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 using namespace std;
int main()
{
int i = 0;
do
{
cout
-
8/16/2019 CS503 Lec5
18/19
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
using namespace std;
int main()
{
int i = 11;
while (i
-
8/16/2019 CS503 Lec5
19/19
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.