CS 1440-Lab 3

Looping

The goals of this lab are to:
1) learn about the while loops
2) learn about the do while 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 Netscape 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.

Activity 3-2: while loop
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.h>
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;
}

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.

An Example for while loop
// P32.C - Read and average 6 integers, print the result.

#include <iostream.h>
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;
}

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.C. 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 use the Edit tab to cut and paste part of the program from this lab manual to the editor screen.  To do this, highlight the text that you wish to copy, go to Edit at the top of this screen, press copy, then go to the editor screen, move the mouse pointer to the location where you want to copy the text, and press the right button of the mouse . You can use the paste option under Edit to do the same thing but some screens may not show the Edit tab.

Exercise 3-2
Change the P32.C program to compute the average of 100 numbers. What are the changes that you need to make?
Save the program under lab3 directory as ex32.C and show it to your instructor in the lab once you completed it.

If you need a hint, check Hint (1) at the end of the this lab.

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 number of values for which he/she wants to find the average, then he/she would enter those values.

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

#include <iostream.h>
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
}

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.  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 choose to do so by entering choice = 1.

#include <iostream.h>
int main(void)
{
int x;
int count = 0;
int N; // Number of values for which the average must be computed.
int choice = 1; // (1) This is to run the program for another set of values or terminate the program.
double sum;
double average;
// prompt the user:
do
{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
count = 0 // (1) initialize a counter to 0 to count number of values for each new set
sum = 0; // set the sum to 0 for each new set
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
}

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

cout << "Do you wish to repeat the program for another set? enter 1 to repeat:  ";
cin >> choice; // (3) change the condition, read a new choice
} while ( choice == 1); // (2) check the boolean expression

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. Show the program to your instructor once you are done.

Remarks

There are two types of looping.  The first type is 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 looping, 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 stop 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 had to terminate is 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 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 your lab3 directory.  Demonstrate the program to the instructor once you are done.

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 EveOdd.C
// Date:           <today's date>
//
// EveOdd.C, This program separates the Even and Odd numbers in two different columns.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
#include <iostream.h>
int main()
{
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 count;  // This is number of values we wish to print in the sequence
int current; // This is a temporary variable

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 << "\nEVEN\tODD\n";

current = start;
while (count > 0)
{
if ((current%2)==1)  //To write the odd numbers on a different column
cout << "\t";
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 uses 2 instead and will replace -2 with 2 as the value for skip.

See Hint (2) at the end of this lab, if you need help.

Exercise 3-6
What do we need to submit for this lab.  First of all make sure you have the following files under your lab3 directory.  To list all files under that directory you can simply use % ls.  You should have the following files, ex31.C, ex32.C, ex33.C, ex34.C, and ex35.C.  You will use the script utility to create one file that contains all these files.  Here is how to do this.

% script        (This starts the script)
% more ex31.C      (Display ex31.C on the)
% more ex32.C      (Display ex32.C on the)
% more ex33.C      (Display ex33.C on the)
% more ex34.C      (Display ex34.C on the)
% more ex35.C      (Display ex35.C on the)

Then  Ctrl-D  (hold the Ctrl then press D)

If you list your files again, % ls, you will see an extra file called typescript in the lab3 directory.  Make sure that that file is there.  If you do not see it, ask the instructor to help you.  You need to print this file and submit it to your instructor.

Now, you need to submit a copy of this file to your instructor using the submit command: (Note ? is your section number).
% ~YourInstrucotrID/bin/submit1440_10?   lab3   typescript      (submits typescript to directory lab3 of your instructor)

Then type:
% ~YourInstrucotrID/bin/submit1440_10?   lab3          (to check if your submission has gone through)

Post Lab

1) Modify the EveOdd.C program so that it takes the following as its input but it generates similar output as the one produced by the original EveOdd.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

Even       Odd
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 hard copy of your program in the lab and submit an electronic copy using the following command:

% ~rt/bin/submit1440_10?  lab3  post3.C

Replace the ? with your section number.

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*(-1)  or abs(skip).