Loops
The syntax for a while loop is:
while( Boolean_Expression)
{
Statement 1;
Statement 2;
...
Statement Last;
}
The part between { and } is called the body of the loop. In a while loop, the body of the loop may be executed 0 times. That means, if the boolean expression evaluates to false right at the beginning, then the body of the loop will not get executed.
There are two types of loops. The first type are controlled by
a counter and they are referred to as "count-controlled" loops. The
second type are controlled by a particular event and they are referred
to as "event-controlled" loops. In this lab, most of the examples
are for count-controlled loops. In either case, there is always a boolean
expression that leads the flow of the computation into the body of the
loop or out of it. To explain the difference between these two types
of loops, let's look at the following two examples:
A) Read 10 integers and compute their sum. A
counter must keep the count until 10 numbers are read.
B) Read integers and compute their sum for as long
as the user keeps entering an integer value and stops once the user enters
a letter. In this case, the event that
stops the loop is the occurrence of a letter.
In either case, if you wish to have a good working loop (any loop),
there are three things that you have to always remember:
1) initialization,
whatever controls the loop and is checked by the boolean expression,
2) valid condition,
the boolean expression must correctly check the controlling variable, and
3) change, the controlling
variable must be changed so that the boolean expression checks a new condition
each time. If the condition does not change in the body of the loop,
then the loop checks the same thing infinite number of times and you will
have an infinite loop. Your program never stops and you have to terminate
it using Ctrl-C or by killing the process. I am sure we will run
into this problem in the lab, so you will learn how.
These three things are marked with (1), (2) and (3), in the P33_2.cpp and P33_3.cpp programs that you will encounter in this lab.
An Example for while loop
The following C++ program computes the average of 6 numbers.
// P33_1.cpp - Read and compute the average for 6 integers, display the result.
#include <iostream>
using namespace std;
int main(void)
{
int
x,y,z, p, q, r; // (A)
double average;
// prompt the user:
cout << "Enter six
grades separated by spaces, then press <Enter>:" << endl;
// read and store six integers:
cin
>> x >> y >> z >> p >> q >> r; // (B)
average
= (x + y + z + p + q + r)/6; // (C)
cout << "The average
is " << average << endl;
return 0;
}
If we wanted to compute the average of three numbers, we could make some changes in this program. The major changes will made in the lines that are in blue font, also, marked with (A), (B), and (C). Imagine, computing the average of 1000 numbers using the above program and method. That would make things more complicated and the code more tedious. We can simplify this computation using a loop. Following is a new version of the above program written using a while loop.
An Example for while loop
// P33_2.cpp - Read and average 6 integers,
print the result.
#include <iostream>
using namespace std;
int main(void)
{
int
x;
int count = 0; // (1) initialize a counter to 0 to count number
of grades
double
sum = 0; // initialize the sum to 0 to make sure the sum at the beginning
is 0
double average;
// prompt the user:
cout << "Enter six
grades separated by a single space, then press <Enter>: ";
while(
count < 6) // (2) read six grades and compute their sum, count
ensures 6 entries
{
// read each number and compute the sum:
cin >> x;
sum = sum + x;
count++; // (3) update the count
}
cout << endl;
average
= sum/6;
// compute the average, total divided by the number of grades
cout << "The average
is " << average << endl;
return 0;
}
Question: What are the differences between this program and the one given in P33_1.cpp?
Exercise
33-1
Use a text editor to create a file called ex33_1.cpp.
Copy and paste or carefully copy P33_2.cpp program in that file, and then
change the program to compute the average of 20 numbers.
Looping with Variable Number
of Loops
There are times that you do not know, up front, how many times a computation
must be done. For example, you do not know how many numbers are going
to be entered every time that you run the program. Thus, you want
to make the loop flexible. Here is another version of the above program
with variable number of loops. Suppose the user first provides number
of values for which he/she wants to find the average, then he/she would
enter those values.
// P33_3.cpp - Read and average N integers, print the result.
#include <iostream>
using namespace std;
int main(void)
{
int
x;
int
count = 0; // (1) initialize a counter to 0 to count number
of values
int
N; // Number of values for which the average must be computed.
double
sum = 0; // initialize the sum to 0 to make sure the sum at the beginning
is 0
double average;
// prompt the user:
cout << "Enter number
of values, N, to be read in <Enter>:"
<< endl;
cin
>> N;
while(
count < N) // (2) read N grades and compute their sum, count
ensures N entries
{
// read each number and compute the sum:
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; // (3) update the count
}
if(N
== 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else{
average
= average = sum/N;
cout << "The average of these " << N << " grades is "
<< average << endl;
}
return 0;
}
Remarks
Now change it again and generalize your program by
creating a file ex33_2.cpp
computing the average for a value N given by the user.
As we mentioned at the beginning, he syntax for a while loop is:
while( Boolean_Expression)
{
Statement 1;
Statement 2;
...
Statement Last;
}
The part between { and } is called the body of the loop. In a while loop, the body of the loop may be executed 0 times. That means, if the boolean expression evaluates to false right at the beginning, then the body of the loop will not get executed.
Sometimes, you may want to execute the body of the loop at least once. In such a case you have to use a do while loop. The syntax for a do while is:
do
{
Statement 1;
Statement 2;
...
Statement Last;
} while( Boolean_Expression);
Exercise
33-2
Change the program P33_3.cpp by replacing the
statement while loop
with a do while loop. Call your new program
ex33_4.cpp. Compile and run the program. The program doesn't
produce the correct result for all the input (ex. for negative values of N).
Why? While still keeping the do while loop command, can you
modify the program so that it produces the correct result?
Exercise 33-3 Change it again and create a file ex33_3.cpp which contains a loop that asks the user if he/she wants to repeat the computation again (Y or N) and let him/her enter new values.