CS 1440 - Lab 3

Looping

Goals
The goals of this lab are to:
1) learn about the while loops
2) learn about the do while loops
3) learn about nested loops

Activity 3-1
You will need to be logged on to the cs machine to do this lab, so get logged in now. (You will then have both a browser
window and a telnet window open.)

Now change to your 1440 subdirectory and create a new directory for this lab. Call it "Lab3". After you create the Lab3
subdirectory, go to that directory. The commands to use to do this are:

% cd 1440              #(This is to change your current directory to 1440)
% mkdir Lab3         #(This is to make a directory call Lab3)
% cd Lab3              #(This is to change your current directory to Lab3)

In this lab, different font colors will be used in example programs, please pay  attention to them to understand the lab better.

Note also that the examples in this lab, like many examples in textbooks, include comments intended for someone new to C++.
Such comments are intended to help you use the example to learn about the language. Some of those comments are ones that
we would not put in programs that we were writing -- their content has too much of the "vocalize the adjacent statement"
flavor.

A Simple C++ Program
In the previous lab, you used a C++ program to compute the average of three integers.  The following example will show how
to compute the average of six integers.

// P31.C - Read and average 6 integers, display the result.

#include <iostream>
int main( )
{
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;
}

As you may have noticed, this program is not much different from the one given in Lab2.  The major changes are made in the
lines that are in blue font, also, marked with (A), (B), and (C).  These changes have made parts (A), (B), and (C) of the code
longer.  You had to: (A) declare three more variables, (B) read three extra variable as well, and (C) finally, you had to consider
them in the calculation of the average.  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.
Activity 3-2 - while-loop
Simple Example using a while loop
// P32.C - Read and average 6 integers, print the result.

#include <iostream>
int main( )
{
int x;
int count;       // counts how many grades so far
double sum;
double average;

// prompt the user:
cout << "Enter six grades separated by a single space, "
<< "then press <Enter>: ";

count = 0;              // (1) so far we've processed 0 grades
sum = 0;                // (1) the sum of zero grades is 0
while( count < 6)   // (2) while number processed is too few
{
// read each number and compute the sum:

cin >> x;             // (4) modify x to be the next number
sum = sum + x;   // (3) add-in the next number
count++;            // (4) update the count
}
cout << endl;

average = sum/6;      // average is total divided by number of grades
cout << "The average is " << average << endl;

return 0;
}

Exercise 3-1
What are the differences between this program and the one given in P31.C?  Use pico to create a file called ex31.txt. On the
first line of this file type your First name, Last name, and ID, then type your answer in that file and save the file under Lab3
directory.

Please be brief.  If you wish, you can copy and paste part of the program from this lab manual to an editor running in a telnet
window.  To do this, you must have both a browser displaying the text you want and a telnet window in which you have started
an editor. The editor must be ready to accept typed-in text. Highlight the text that you wish to copy from the browser. Go to
the Edit menu at the top of the browser window and choose copy. Then go to the telnet window. Move the cursor to the
location where you want to copy the text. (With pico you'll use the arrow keys to do this.) Press the right button of the mouse.
You can use the paste option under Edit to do the same thing but some windows may not show the Edit menu.

Exercise 3-2
Change the P32.C program to compute the average of 100 numbers using a loop. What are the changes that you need to
make?
Save the program in Lab3 directory as ex32.C.

If you need a hint, click this: Hint (1).

Activity 3-3 - Looping with Variable Number of Loops
Now, let's look at another version of the above program.  Suppose the user first provides the number of values for which she
wants to find the average, then she would enter those values.

// P33.C - Read and average N integers, print the result.

#include <iostream>
int main( )
{
int x;

int N;               // Number of values to average.
int count;          // the number of grades processed so far
double sum;
double average;

cout << "Enter number of values, N, to be read in. "
<< "Then press <Enter>:" << endl;
cin >> N;

count = 0;          // (1) so far we've processed 0 grades
sum = 0;            // (1) the sum of 0 grades is 0

while( count < N)     // (2) while we haven't yet used enough grades
{
// read each number and compute the sum:

cout << "\n Enter a grade and press <Enter>: ";
cin >> x;                // (4) modify x to be the next number
sum = sum + x;      // (3) add-in the next number
count++;               // (3) update the count
}

average = sum/N;
cout << "The average of these " << N << " grades is " << average << endl;

return 0;
}

Activity 3-4 - Nested loops
Now, let's look at another version of the above program.  Suppose the user will not only provide the number of values for
which he/she wants to find the average, but also he/she will tell us whether he/she wants to compute another set of values once
he/she is done with one set. (For example, to average grades for test 1 first then for test 2.)  In the following example the user
enters 1 when she/he wants to repeat the program for a new set, and enters any other number to stop the computation.

// P34.C - Read and average N integers, print the result.
// This program repeats the computation for a new set of numbers,
// if the user chooses to do so by entering a choice of 1.

#include <iostream>
int main( )
{
int x;
int count ;
int N;               // Number of values to average.
int choice;        // (1) Run the program for another set of values?
double sum;
double average;

do
{
cout << "Enter number of values, N, to be read in. "
<< "Then press <Enter>:" << endl;
cin >> N;
count = 0;          // (1) so far we've used 0 grades in this set
sum = 0;            // (1) the sum of 0 grades is 0
while( count < N)    // (2) while we haven't yet used enough grades
{
// read each number and compute the sum:
cout << "\n Enter a grade and press <Enter>: ";
cin >> x;
sum = sum + x;
count++;     // (3) we've used one more
}

average = sum/N;
cout << "The average of these " << N << " grades is "
<< average << endl;

cout << "Repeat the program for another set? enter 1 to repeat:  ";

cin >> choice;                 // (3) choice remembers user's answer
} while (choice == 1);          // (2) act on the choice

return 0;
}

Exercise 3-3
Change the above program so that it repeats the calculations for as long as the choice is not equal 0.  Thus, if the user inputs 0
for choice, the program will be terminated, otherwise it will continue the computations. Call your new program ex33.C and
save it in your Lab3 directory.

Remarks

There are two types of loops.  The first type is controlled by a counter and is referred to as a "count-controlled" loop.  The
second type is controlled by a particular event and is referred to as an "event-controlled" loop.  In this lab, most of the
examples are count-controlled loops. In either case, there is always a Boolean expression that controls 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. In this case, a counter must keep the count of how many integers have been
B) Read integers and compute their sum for as long as the user keeps entering a positive integer value and stop once the user
enters a zero.   In this case, the event that stops the loop is the user entering a zero.

In any case, if you wish to have a working loop (any loop), there are some things that you have to always remember. Every
working loop contains the following four functional elements:

1.Initialization
Gives a starting value to whatever controls the loop (to whatever is checked by the Boolean expression). Gives a starting
value to "scratch" variables of the loop -- especially ones "accumulating" a value". This part is performed only once and is
done at the beginning.
2.A test
This part "decides" whether to repeat the body of the loop or to quit; in C++ it is phrased as, "Should I repeat the
body?" The Boolean expression must correctly check the controlling variable.
3.Progress
Something in the loop body must make progress toward the intended result. Often that element is an instance of a
pattern to repeat that you identified when you decided to write a loop.
4.Modification or change
Something in the repeated part must change in a way that affects the test, and something must change so that the
statement of #3 doesn't do exactly the same thing each time through the loop. Typically a controlling variable is changed
so that the Boolean expression checks a new condition each time.  If nothing affecting the test (the Boolean expression)
changes in the body of the loop, then the outcome of the test is always the same 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 things are marked with (1), (2), (3), and (4), in the P32.C and P33.C programs.

The syntax for a while loop is:

while( Boolean_Expression)
{
Statement 1;
Statement 2;
...
Statement Last;
}

The part between { and } are 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 3-4
Change program P33.C to work with a do while loop instead of while loop.  Call your new program ex34.C and save it in

Activity 3-5
A More Complicated Example for while loop
Here is a small C++ program that prints the odd and even numbers between an initial number and another number in two
different columns.

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Program ex35.C
// Date:           <today's date>
// Programmer:     <your name>
//
// ex35.C,
// This program separates the Even and Odd numbers in two

// different columns.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
#include <iostream>
int main()
{
int start;     // The starting value of the sequence.
int skip;      // We skip size from one number to the next).
int count;     // The number of values we wish to print
int current;   // A number in the sequence

cout << "This program prints out a sequence of numbers\n"
<< "and places each number in a column labeled EVEN if\n"
<< "it is an even number and a column ODD if it is an odd\n"
<< "number.  You are to specify three values:\n"
<< "(1) a starting value for the first number to print\n"
<< "(2) a 'skip' value for the difference between two\n"
<< "    successive numbers, and\n"
<< "(3) a count for the number of items to be printed.\n"
<< "After you have specified these values, the table of\n"
<< "data will be printed\n\n";

cout << "Enter the starting value: ";
cin  >> start;

cout << "\nEnter the skip value: ";
cin  >> skip;

cout << "\nEnter the number of items to be printed: ";
cin  >> count;

cout << "\nODD\tEVEN\n";

current = start;
while (count > 0)
{
if ((current%2)==0) cout << "\t"; //Evens go farther right
cout << current << endl;
count -=1;
current += skip;
}
cout << "\nThanks for using this program.\n";
return 0;
}

Exercise 3-5
Save the above program in a file called ex35.C in Lab3 subdirectory. Compile and run the program.  Now, make a change in
this program to avoid using a negative value for skip in your calculations.  Thus, if the user enters a negative value for skip, the
program will change that value to its positive equivalent.  For example, if a user enters -2 for the value of skip, the program
displays a message that it will use 2 instead and will replace -2 with 2 as the value for skip.

See Hint (2) if you need help.

Post Lab

1) Modify the ex35.C program so that it takes the following as its input but it generates similar output as the one produced by
the original ex35.C program. Call the new program post3.C.

The inputs are :
int start;        // This is the starting value of the sequence.
int skip;        // This is step size (values that we skip from one number to the next).
int end;        // This is the ending value of the sequence

Note that, this time instead of counting some numbers we will end the sequence once we reached the end value.

Example:
start = 1
skip = 3
end = 14

Odd       Even
1
4
7
10
13

Since the next number 13+3 = 16 is larger than 14 we stop the program at this point.

Turn in a program listing of your program.

Hints
** Hint (1): You only need to change the numbers in bold red font to 100 instead of 6. How simple.
** Hint (2):  Right after :
cout << "\nEnter the skip value: ";
cin >> skip;

use an if statement to check whether skip is negative or not.  if it is replace it with skip = -skip .